Edit: I've removed the faster/more efficient from the question title as it was misleading..my intention was not optimisation but understanding arrays. Sorry for the trouble!
int array[10][10], i, j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[i][j];
}
Versus
int array[10][10], i, j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[j][i];
}
I'm pretty sure the answer has to do with how arrays are implemented on a hardware level; that the [ ][ ] syntax is just a programmer's abstraction to aid visualisation/modelling. However, I forgot which of the above code accesses the memory block sequentially from start till end...
Thanks for all the answers...
Just to confirm my understanding, does this mean the first code is equivalent to
int array[10][10], k;
for(k=0;k<100;k++)
{
std::cin>>*(array+k);
}
Aside from the fact that waiting on getting user input will be signifficantly slower than the array access, the first one is faster.
Check out this page on 2D array memory layout if you want more background on the subject.
With the second one you are checking A[0], A[10] ... A[1], A[11].
The first is going sequentially A[0], A[1], A[2] ..
The first one has better spatial locality. Because the first subscript is the index of a subarray, and the second subscript is the element within that subarray; so when you fix i
and vary the j
's, you are looking at elements that are all within a subarray and thus are close together; but when you fix j
and vary the i
's, you are looking at elements that are 10 (the length of a subarray) apart, so are very spread out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With