Doubt - Static multidimension arrays

Nemo via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 20 17:36:21 PST 2016


On Tuesday, 19 January 2016 at 20:39:37 UTC, tsbockman wrote:
> On Tuesday, 19 January 2016 at 19:14:30 UTC, alb wrote:
>>    [...]
>
> One other thing you may want to keep in mind when working on 
> this kind of thing - when you loop over a multi-dimensional 
> array, the order matters.
>
> For large arrays, this:
>
>     int[c_max][r_max] arr;
>
>     foreach(r; 0 .. r_max)
>     {
>         foreach(c; 0 .. c_max)
>         {
>             // do something with arr[r][c] here
>         }
>     }
>
> Can be *much* faster than this:
>
>     int[c_max][r_max] arr;
>
>     foreach(c; 0 .. c_max)
>     {
>         foreach(r; 0 .. r_max)
>         {
>             // do something with arr[r][c] here
>         }
>     }
>
> The reason is that the first version access the elements in the 
> order that they are actually stored in memory, whereas the 
> second forces the CPU to jump between rows for each element.
>
>> [...]
>
> You're welcome.
>
> And yes, it can definitely be confusing. I understand why the 
> array syntax in D is the way it is, but that still doesn't 
> always save me from mixing things up once in a while anyway.

I don't remember where I saw it, but actually, in static 
multi-dimensional arrays, arr[0][1] is next to arr[0][0] in 
memory. You can see it with:

void main () {
   ubyte [7][5] arr;
   import std.stdio : writeln;
   writeln ( & arr[0][0], " ", & arr[0][1], " ", & arr [1][0] );
}


More information about the Digitalmars-d-learn mailing list