Following this question "What is “cache-friendly” code?" I've created dynamic 2d array to check how much time would it take to access elements column-wise and row-wise.
When I create an array in the following way:
const int len = 10000;
int **mass = new int*[len];
for (int i = 0; i < len; ++i)
{
mass[i] = new int[len];
}
it takes 0.239 sec to traverse this array row-wise and 1.851 sec column-wise (in Release).
But when I create an array in this way:
auto mass = new int[len][len];
I get an opposite result: 0.204 sec to traverse this array row-wise and 0.088 sec column-wise.
My code:
const int len = 10000;
int **mass = new int*[len];
for (int i = 0; i < len; ++i)
{
mass[i] = new int[len];
}
// auto mass = new int[len][len]; // C++11 style
begin = std::clock();
for (int i = 0; i < len; ++i)
{
for (int j = 0; j < len; ++j)
{
mass[i][j] = i + j;
}
}
end = std::clock();
std::cout << "[i][j] " << static_cast<float>(end - begin) / 1000 << std::endl;
begin = std::clock();
for (int i = 0; i < len; ++i)
{
for (int j = 0; j < len; ++j)
{
mass[j][i] = i + j;
}
}
end = std::clock();
std::cout << "[j][i] " << static_cast<float>(end - begin) / 1000 << std::endl;
Please, can you explain what is the difference between these ways to allocate memory for two-dimentional dynamic array? Why does it faster to traverse array row-wise in first way and column-wise in second way?