实现一个更有效的矩阵 - 使用数组数组(二维)还是一维数组?

实现一个更有效的矩阵 - 使用数组数组(二维)还是一维数组?

问题描述:

当使用数组实现矩阵构造时,哪个更有效?使用一维数组还是数组数组(二维)?

When implementing a Matrix construct using arrays, which would be more efficient? Using a 1D array, or an array of arrays (2D)?

我认为 2D 更有效,因为您已经拥有元素的 X 和 Y 坐标,而在 1D 实现中,您必须计算索引.

I would think a 2D is more efficient as you already have the X and Y coordinates of an element, where in a 1D implementation you have to calculate the index.

它是使用 Java 实现的

it is being implemented using Java

高效"并不是一个包罗万象的术语.

"Efficient" is not a catch-all term.

array-of-arrays 解决方案在存储方面更有效,其中数组可能是稀疏的(即,您可以使用空指针来表示全零的矩阵线).这将是(在 C 中):

An array-of-arrays solution is more efficient in terms of storage, where the array may be sparse (i.e., you can use null pointer to represent a matrix line of all zeroes). This would be (in C):

int *x[9];

其中每个 "int *" 将单独分配.

where each "int *" would be allocated separately.

二维数组(不一定是数组的数组)通常会更快(就速度而言是有效的),因为它使用数学计算出内存位置,而无需取消引用内存位置.我说的是构造:

A 2D array (which is not necessarily an array of arrays) will generally be faster (efficient in terms of speed) since it works out memory locations with math, without having to de-reference memory locations. I'm talking of the construct:

int x[9][9];

形式为一维数组:

int x[81];

不太可能比等效的 2D 版本更快,因为您仍然需要在某个时候进行计算才能找到正确的单元格(在您的代码中手动而不是让编译器这样做).

is unlikely to be any faster than the equivalent 2D version since you still have to do the calculations at some point to find the correct cell (manually in your code rather than letting the compiler do it).

在添加 Java 作为要求的地方进行编辑后:

我相信 Java 2D 数组属于各种数组的数组(这需要两次内存访问,而不是一维数组所需的一次),因此具有手动索引计算的一维数组可能会更快.因此,与其声明和使用:

I believe Java 2D arrays are of the array of arrays variety (which will require two memory accesses as opposed to the one required for a 1D array) so the 1D array with manual index calculation may well be faster. So, instead of declaring and using:

int x[width][height];
x[a][b] = 2;

您可以通过以下方式获得更快的速度:

you may get more speed with:

int x[width*height];
x[a*height+b] = 2;

您只需要注意不要在任何地方混淆公式(即不要无意中交换 4 和 7).

You just need to be careful that you don't get the formula mixed up anywhere (i.e., don't swap 4 and 7 inadvertently).

这种速度差异是基于我认为 Java 在幕后编码的方式,所以我可能是错的(但我对此表示怀疑 :-).我的建议是,对于优化问题,衡量,不要猜测!

This speed difference is based on how I think Java is coded under the covers so I could be wrong (but I doubt it :-). My advice is, as always for optimisation questions, measure, don't guess!