2维阵列的性能对1维阵列 [英] Performance of 2-dimensional array vs 1-dimensional array

查看:102
本文介绍了2维阵列的性能对1维阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,是有在时间和m×n个2维阵列之间VS长度m×n个的一维阵列的差分空间(并且m大值N)?访问元素将与一维数组更快?

In C, is there a difference in time and space between an m x n 2-dimensional array vs a 1-dimensional array of length mxn (for large values of m and n)? Will accessing elements be faster with a 1-dimensional array?

推荐答案

在C,2维数组只是一维数组整齐的索引方案。就像使用一维数组,二维数组分配的连续内存的单块,而A [行] [COL]符号就像是说A [*行+ NCOLS山坳。

In C, 2-dimensional arrays are just a neat indexing scheme for 1-dimensional arrays. Just like with a 1D array, 2D arrays allocate a single block of contiguous memory, and the A[row][col] notation is just like saying A[row*NCOLS+col].

通常,如果你要实现使用单维数组自己的多维数组,你会写一个分度功能:

Usually if you were to implement your own multidimensional arrays using single dimensional arrays, you'd write an indexing function:

int getIndex(int row, int col) return row*NCOLS+col;

假设你的编译器内联此功能,在这里的表现将是precisely一样,如果你使用了内置的二维数组索引功能。

Assuming your compiler inlines this function, the performance here would be precisely the same as if you used the built in 'indexing function' of 2D arrays.

要说明:

#define NROWS 10
#define NCOLS 20

int main(int argc, char *argv[]) {
    int myArr[NROWS*NCOLS];
    for (int i=0; i<NROWS; ++i) {
       for (int j=0; j<NCOLS; ++j) {
          myArr[getIndex(i,j)] = i+j;
       }
    }
    return 0;
}

应该执行相同的,因为这

Should perform the same as this:

int main(int argc, char *argv[]) {
    int myArr[NROWS][NCOLS];
    for (int i=0; i<NROWS; ++i) {
       for (int j=0; j<NCOLS; ++j) {
          myArr[i][j] = i+j;
       }
    }
    return 0;
}

虽然为阿拉克指出的那样,如果你周围跳跃行很多,而行是非常大的,你可以打了很多的页面错误......在这种情况下,自定义索引功能(带有行列数切换左右)可以帮助,但这样可以简单地改变其在2维阵列的尺寸的你视为行和你视为列。

Though as AraK pointed out, if you are jumping around rows alot, and the rows are very large, you could hit a lot of page faults... in that case the custom indexing function (with rows and cols switched around) could help, but so could simply changing which of the dimensions in a 2-dimensional array you treat as the rows and which you treat as the columns.

这篇关于2维阵列的性能对1维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆