Array or List in Java. Which is faster?

后端 未结 30 1619
滥情空心
滥情空心 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 agree that in most cases you should choose the flexibility and elegance of ArrayLists over arrays - and in most cases the impact to program performance will be negligible.

    However, if you're doing constant, heavy iteration with little structural change (no adds and removes) for, say, software graphics rendering or a custom virtual machine, my sequential access benchmarking tests show that ArrayLists are 1.5x slower than arrays on my system (Java 1.6 on my one year-old iMac).

    Some code:

    import java.util.*;
    
    public class ArrayVsArrayList {
        static public void main( String[] args ) {
    
            String[] array = new String[300];
            ArrayList list = new ArrayList(300);
    
            for (int i=0; i<300; ++i) {
                if (Math.random() > 0.5) {
                    array[i] = "abc";
                } else {
                    array[i] = "xyz";
                }
    
                list.add( array[i] );
            }
    
            int iterations = 100000000;
            long start_ms;
            int sum;
    
            start_ms = System.currentTimeMillis();
            sum = 0;
    
            for (int i=0; i

提交回复
热议问题