My question is about efficiency of accessing elements of a double std::array
. Since the std::array
is a static-sized container, I expect its data to be stored in a continuous block of memory and accessing the elements of the std::array
to be same as C-style arrays. The use of std::array
should not add any additional overhead.
Is accessing elements of double arrays std::array<std::array<T,N>,M>
optimised?
For example I have to source code below.
#include <array>
#include <random>
int main(){
std::array<std::array<int,4>,2> a;
for(int j=0;j<4;j++)
a[0][j] = rand();
for(int j=0;j<4;j++)
a[1][j] = rand();
int r = a[0][1] + a[1][3];
return r;
}
- Does
a
uses a single block of memory? - Is accessing an element with constant indices (ie
a[1][3]
) a single or a double shift in memory? - How many shifts is needed in accessing the element in a loop (ie
a[1][j]
)
I used godbolt.org in the above example to check the assembly code and it seems that gcc -O4
does a pretty good job.
For example access to a[1][3]
and a[0][1]
is compiled as :
mov eax, DWORD PTR [rsp+28]
add eax, DWORD PTR [rsp+4]
However can I use this finding in a more complex example?
Or should I stick to simple std::arrays
to control access efficiency?
Is there any ISO standards description in the double std::array
?