java - 读取/存储大量多维数据的最快方法? ( java )

标签 java performance data-structures arrays multidimensional-array

我有三个关于三个嵌套循环的问题:

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/

相关文章:

c - 如何评估无锁队列的性能?

c++ - unordered_map 的正确值

java - 在Java中实例化大量子类的最有效方法?

java - Martin Fowler 在 REST API 中所说的 "avoid automatic deserialization"是什么意思?

java - 从选项卡 Activity android 传递额外内容

java - 没有对象的语句错误

c# - 如何提高 Bouncy CaSTLe API 的加密速度?

java - 为什么 Open 和 Oracle JDK 在 Raspberry pi 上的性能差异如此之大?

data-structures - 如何使用两个堆栈实现双端队列

java - 为什么 Stack 使用基于 1 的索引而不是像 Java 中的数组那样使用基于 0 的索引?