Dynamic array comparison optimization: check for equal pointers?

Stanislav Blinov stanislav.blinov at gmail.com
Tue Jun 2 22:20:03 UTC 2020


On Tuesday, 2 June 2020 at 22:01:20 UTC, Johan wrote:
> On Tuesday, 2 June 2020 at 20:54:39 UTC, Stanislav Blinov wrote:

>> That's, worst case, two branches and a scan, and best case one 
>> branch which may or may not be slower than the actual scan.
>
> The "actual scan" is a function call, which will be super slow 
> (note that in druntime's implementation it cannot be optimized 
> to a tail call) compared to the comparison and early return.

LDC (and I'm assuming GDC as well) is well aware of memcmp, it 
should not be a function call. At the very least in -Ox builds.

> You are assuming that an if-statement costs significant time, 
> but that doesn't have to be the case. The pointer values 
> already must be read from memory (otherwise you cannot do the 
> memory scan), and with speculative execution the 
> comparison+branch only costs very little (codegen could be 
> coaxed to make if(false) be the default execution path) and 
> potentially saves many many memory reads.

I'm not assuming anything. The branch(es) may, or may not, be 
more costly than just comparing some words. Depending on 
architecture and the amount of data to compare. That's literally 
what I wrote :) May, or may not - implementation has no business 
assuming either way. That's why such a check absolutely should 
*not* be there. It should be where it belongs - in user code, 
backed up by profiling as necessary.
Including it there may be beneficial for you specifically, but 
detrimental for everyone else.


More information about the Digitalmars-d mailing list