Array fill performance differences between for, foreach, slice

Steven Schveighoffer schveiguy at gmail.com
Wed Apr 1 02:24:55 UTC 2020


On 3/31/20 5:30 PM, data pulverizer wrote:
> I've observed large differences in timing performance while filling 
> arrays using different methods (for vs foreach vs arr[] = x) and don't 
> know why. I've looked at array.d 
> (https://github.com/dlang/dmd/blob/9792735c82ac997d11d7fe6c3d6c604389b3f5bd/src/dmd/root/array.d) 
> but I'm still none the wiser.

for: you are indexing an array on each step, incurring a bounds check, 
and also doing a pointer calculation on each access.

foreach: Better, iterates a pointer over the whole array, so it's going 
to be faster.

slice assign: Best, this uses whatever tricks are possible in the given 
architecture. Most likely memset, or memcpy. These are insanely 
optimized functions, which is why they perform so well.

-Steve


More information about the Digitalmars-d-learn mailing list