Overhead when accessing a 2d array in linear memory space

Is the addressing of addressing values ​​in a multidimensional array in a linear manner, as in

values[row_num*row_width + column_num]

take additional calculations for multiplication / addition compared to the values ​​of [row] [col]? Or does the compiler convert the last to the first?

+3
source share
3 answers

Assuming you are comparing indexing, for example. int values[M*N]and int values[M][N]accordingly, in practice they will create equivalent code.

However, if you use values[row][col]for indexing, for example. int (*values)[N]then this is another matter ...

+1
source

. :

int values[m][n];

, (, ).

:

int **values;
values = new int*[m];
for (size_t i = 0; i < m; ++i) values[i] = new int[n];

,

values[row][col]
// same as
*(*(values+row) + col)

.. . , , , ( , ) .

+1

?

Yes. If you index consecutive memory locations, caching will work in your favor, a long time.

0
source

Source: https://habr.com/ru/post/1762535/


All Articles