By ref and by pointer kills performance.

Patrick Schluter Patrick.Schluter at bbox.fr
Tue Feb 13 15:11:58 UTC 2024


On Tuesday, 13 February 2024 at 02:11:45 UTC, claptrap wrote:
> I was refactoring some code and changed a parameter from by 
> value, to by pointer, and saw the performance drop by 50%. This 
> is a highly reduced example of what I found, but basically 
> passing something into a function by reference or pointer seems 
> to make the compilers (it affects both DMD and LDC) treat it as 
> if its volatile and must be loaded from memory on every use. 
> This also inhibits the auto-vectorization of code by LDC.
>
> https://d.godbolt.org/z/oonq1drd9
>
> ```d
> void fillBP(uint* value, uint* dest)
> {
>     dest[0] = *value;
>     dest[1] = *value;
>     dest[2] = *value;
>     dest[3] = *value;
> }
> ```
> codegen DMD -->
>
>                 push    RBP
>                 mov     RBP,RSP
>                 mov     ECX,[RSI]
>                 mov     [RDI],ECX
>                 mov     EDX,[RSI]
>                 mov     4[RDI],EDX
>                 mov     R8D,[RSI]
>                 mov     8[RDI],R8D
>                 mov     R9D,[RSI]
>                 mov     0Ch[RDI],R9D
>                 pop     RBP
>                 ret
>
> codgen LDC -->
>
>         mov     eax, dword ptr [rdi]
>         mov     dword ptr [rsi], eax
>         mov     eax, dword ptr [rdi]
>         mov     dword ptr [rsi + 4], eax
>         mov     eax, dword ptr [rdi]
>         mov     dword ptr [rsi + 8], eax
>         mov     eax, dword ptr [rdi]
>         mov     dword ptr [rsi + 12], eax
>         ret
> ```d

Yes, that's normal. The compiler cannot know from the declaration 
alone if your pointer overlaps. In C you can declare the pointers 
with restrict which will tell the compiler that the pointers 
don't overlap. I don't know why D doesn't support restrict.




More information about the Digitalmars-d mailing list