foreach (i; taskPool.parallel(0..2_000_000)

Steven Schveighoffer schveiguy at gmail.com
Wed Apr 5 22:50:27 UTC 2023


On 4/5/23 6:34 PM, Paul wrote:
> On Tuesday, 4 April 2023 at 22:20:52 UTC, H. S. Teoh wrote:
> 
>> Best practices for arrays in hot loops:
>> - Avoid appending if possible; instead, pre-allocate outside the loop.
>> - Where possible, reuse existing arrays instead of discarding old ones
>>   and allocating new ones.
>> - Use slices where possible instead of making copies of subarrays (this
>>   esp. applies to strings).
>> - Where possible, prefer sequential access over random access (take
>>   advantage of the CPU cache hierarchy).
> 
> Thanks for sharing Teoh!  Very helpful.
> 
> would this be random access? for(size_t i; i<arr.length; i++) using 
> indices?
> ...and this be sequential foreach(a;arr) ?

No, random access is access out of sequence. Those two lines are pretty 
much equivalent, and even a naive compiler is going to produce exactly 
the same generated code from both of them.

A classic example is processing a 2d array:

```d
for(int i = 0; i < arr[0].length; ++i)
    for(int j = 0; j < arr.length; ++j)
      arr[j][i]++;

// vs
for(int j = 0; j < arr.length; ++j)
    for(int i = 0; i < arr[0].length; ++i)
      arr[j][i]++;
```

The first accesses elements *by column*, which means that the array data 
is accessed non-linearly in memory.

To be fair, both are "linear" in terms of algorithm, but one is going to 
be faster because of cache coherency (you are accessing sequential 
*hardware addresses*).

-Steve


More information about the Digitalmars-d-learn mailing list