Array or List in Java. Which is faster?

后端 未结 30 2122
滥情空心
滥情空心 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:12

    I wrote a little benchmark to compare ArrayLists with Arrays. On my old-ish laptop, the time to traverse through a 5000-element arraylist, 1000 times, was about 10 milliseconds slower than the equivalent array code.

    So, if you're doing nothing but iterating the list, and you're doing it a lot, then maybe it's worth the optimisation. Otherwise I'd use the List, because it'll make it easier when you do need to optimise the code.

    n.b. I did notice that using for String s: stringsList was about 50% slower than using an old-style for-loop to access the list. Go figure... Here's the two functions I timed; the array and list were filled with 5000 random (different) strings.

    private static void readArray(String[] strings) {
        long totalchars = 0;
        for (int j = 0; j < ITERATIONS; j++) {
            totalchars = 0;
            for (int i = 0; i < strings.length; i++) {
                totalchars += strings[i].length();
    
            }
        }
    }
    
    private static void readArrayList(List stringsList) {
        long totalchars = 0;
        for (int j = 0; j < ITERATIONS; j++) {
            totalchars = 0;
            for (int i = 0; i < stringsList.size(); i++) {
                totalchars += stringsList.get(i).length();
            }
        }
    }
    

提交回复
热议问题