我有三个关于三个嵌套循环的问题:
for (int x=0; x<400; x++)
{
for (int y=0; y<300; y++)
{
for (int z=0; z<400; z++)
{
// compute and store value
}
}
}
我需要存储所有计算值。我的标准方法是使用 3D 数组:
values[x][y][z] = 1; // test value
但事实证明这很慢:完成这个循环需要 192 毫秒,其中单个 int 赋值
int value = 1; // test value
仅需 66 毫秒。
1) 为什么数组这么慢?
2)当我把它放在内部循环中时,为什么它会变得更慢:
values[z][y][x] = 1; // (notice x and z switched)
这需要超过 4 秒!
3) 最重要的是:我能否使用一种与分配单个整数一样快的数据结构,但可以存储与 3D 数组一样多的数据?
最佳答案
public static void main( String[] args ) {
int[][][] storage = new int[ 400 ][ 300 ][ 400 ];
long start = System.currentTimeMillis();
for ( int x = 0; x < 400; x++ ) {
for ( int y = 0; y < 300; y++ ) {
for ( int z = 0; z < 400; z++ ) {
storage[x][y][z] = 5;
}
}
}
long end = System.currentTimeMillis();
System.out.println( "Time was: " + ( end - start ) / 1000.0 + " seconds." );
}
运行 -Xmx1g
时间为:0.188 秒。
这看起来相当快..您正在查看最内层循环中的 4800 万个元素。
滚动一个愚蠢的小数据结构..
public static void main( String[] args ) {
StorerGuy[] storerGuys = new StorerGuy[ 400 ];
long start = System.currentTimeMillis();
for ( int x = 0; x < 400; x++ ) {
for ( int y = 0; y < 300; y++ ) {
for ( int z = 0; z < 400; z++ ) {
storerGuys[x] = new StorerGuy( x, y, z, 5 );
}
}
}
long end = System.currentTimeMillis();
System.out.println( "Time was: " + ( end - start ) / 1000.0 + " seconds." );
}
public static class StorerGuy {
public int x;
public int y;
public int z;
public int value;
StorerGuy( int x, int y, int z, int value ) {
this.x = x;
this.y = y;
this.z = z;
this.value = value;
}
}
时间为:0.925 秒。
这比您在混合订单示例中的 4 秒快。
我认为多数组对于这个问题来说太多了。您最好使用更复杂的数据结构,因为它将所有内容保存在 1 个内存位置(x、y、z、值)中。
Java 是一种面向对象的语言。在大多数情况下,你应该使用对象而不是奇怪的数据结构,比如 int[][][]
关于java - 读取/存储大量多维数据的最快方法? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2966965/