Array or List in Java. Which is faster?

后端 未结 30 2178
滥情空心
滥情空心 2020-11-22 04:30

I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?

Since arrays keep

30条回答
  •  不知归路
    2020-11-22 05:07

    I came here to get a better feeling for the performance impact of using lists over arrays. I had to adapt code here for my scenario: array/list of ~1000 ints using mostly getters, meaning array[j] vs. list.get(j)

    Taking the best of 7 to be unscientific about it (first few with list where 2.5x slower) I get this:

    array Integer[] best 643ms iterator
    ArrayList best 1014ms iterator
    
    array Integer[] best 635ms getter
    ArrayList best 891ms getter (strange though)
    

    - so, very roughly 30% faster with array

    The second reason for posting now is that no-one mentions the impact if you do math/matrix/simulation/optimization code with nested loops.

    Say you have three nested levels and the inner loop is twice as slow you are looking at 8 times performance hit. Something that would run in a day now takes a week.

    *EDIT Quite shocked here, for kicks I tried declaring int[1000] rather than Integer[1000]

    array int[] best 299ms iterator
    array int[] best 296ms getter
    

    Using Integer[] vs. int[] represents a double performance hit, ListArray with iterator is 3x slower than int[]. Really thought Java's list implementations were similar to native arrays...

    Code for reference (call multiple times):

        public static void testArray()
        {
            final long MAX_ITERATIONS = 1000000;
            final int MAX_LENGTH = 1000;
    
            Random r = new Random();
    
            //Integer[] array = new Integer[MAX_LENGTH];
            int[] array = new int[MAX_LENGTH];
    
            List list = new ArrayList()
            {{
                for (int i = 0; i < MAX_LENGTH; ++i)
                {
                    int val = r.nextInt();
                    add(val);
                    array[i] = val;
                }
            }};
    
            long start = System.currentTimeMillis();
            int test_sum = 0;
            for (int i = 0; i < MAX_ITERATIONS; ++i)
            {
    //          for (int e : array)
    //          for (int e : list)          
                for (int j = 0; j < MAX_LENGTH; ++j)
                {
                    int e = array[j];
    //              int e = list.get(j);
                    test_sum += e;
                }
            }
    
            long stop = System.currentTimeMillis();
    
            long ms = (stop - start);
            System.out.println("Time: " + ms);
        }
    

提交回复
热议问题