高效执行Java中多维数组的? [英] Efficient implementation of multi-dimensional arrays in Java?
问题描述
据我所知(从答案,如<一个href=\"http://stackoverflow.com/questions/732684/implementing-a-matrix-which-is-more-efficient-using-an-array-of-arrays-2d-or/732688#732688\">this), Java没有本地多维连续存储器阵列(不像C#,例如)。
As far as I understand (from answers such as this), java has no native multi-dimensional continuous memory arrays (unlike C#, for example).
虽然交错数组语法(数组的数组)可能是好于大多数应用,我还是想知道什么是最好的做法,如果你确实需要一个连续存储器阵列的原始效率(避免不必要的内存读取)
While the jagged array syntax (arrays of arrays) might be good for most applications, I would still like to know what's the best practice if you do want the raw efficiency of a continuous-memory array (avoiding unneeded memory reads)
我当然可以使用映射到一个二维一个一维数组,但我preFER事情更有条理。
I could of course use a single-dimensional array that maps to a 2D one, but I prefer something more structured.
推荐答案
这取决于您的访问模式。使用这个简单的程序,比较了 INT [] []
与2D映射,以作为基质处理一维 INT []
阵列,本地Java 2D矩阵是:
It depends on your access pattern. Using this simple program, comparing an int[][]
with a 2D mapped over a 1D int[]
array treated as a matrix, a native Java 2D matrix is:
- 25%的速度时,行上的缓存,即:按行访问:
- 慢100%,当行不在缓存中,即:由colums访问:
例如:
// Case #1
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
// Access item[y][x]
// Case #2
for (x = 0; x < w; x++)
for (y = 0; y < h; y++)
// Access item[y][x]
一维矩阵的计算公式为:
The 1D matrix is calculated as:
public int get(int x, int y) {
return this.m[y * width + x];
}
这篇关于高效执行Java中多维数组的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!