Fastest way to read/store lots of multidimensional data? (Java)

前端 未结 5 1369
萌比男神i
萌比男神i 2021-01-02 18:14

I have three questions about three nested loops:

for (int x=0; x<400; x++)
{
    for (int y=0; y<300; y++)
    {
        for (int z=0; z<400; z++)
          


        
5条回答
  •  情话喂你
    2021-01-02 18:37

    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." );
    
    
    }
    

    Ran with -Xmx1g

    Time was: 0.188 seconds.

    That seems pretty darn fast.. you are looking at 48 MILLION elements in the innermost loop.

    Homerolling a silly little datastructure..

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

    Time was: 0.925 seconds.

    Which is faster than 4 seconds you had in your mixed up order example.

    I think multi arrays are too much for the problem. You are better off with a more complex data structure, as it will keep the stuff all in 1 memory location (x,y,z,value).

    Java is an OO language. In most cases, you should use objects and not weird data structures like int[][][]

提交回复
热议问题