实现一个矩阵,这是更有效 - 用一个数组的数组(2D)或一维数组?

实现一个矩阵,这是更有效 - 用一个数组的数组(2D)或一维数组?

问题描述:

在实现使用数组矩阵结构,这将是更有效率?
使用一维数组,或数组(2D)的阵列?

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坐标。

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.

阵列的阵列的解决方案是存储,数组可能是稀疏的(即,您可以使用空指针重新present全零矩阵线)方面更有效率。这将是(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 *将被单独分配。

一个二维阵列(其不一定是数组的数组)通常将快(高效在速度方面),因为它的工作原理进行与数学的存储器位置,而不必去参考存储器位置。我说的构造:

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];

形式的一维数组:

A 1D array of the form:

int x[81];

是不太可能的任何比等效2D版本速度更快,因为你还要做计算在某些时候,找到正确的单元格(在你的code手动而不是让编译器做到这一点)。

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的二维数组的数组多种阵列(这将需要访问两次内存,而不是为一维数组所需要的)所以一维数组与手动指数计算可能会更快的。所以,与其声明和使用:

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是在幕后$ C $的CD,所以我可能是错的(但我:-)怀疑。我的建议是,一如继往地为优化问题,的的措施,不用猜!

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!