java List遍历性能比较

一、测试代码

public class ListPerformanceTest {
    public static void main(String[] args) {
        List<Integer> arrayList = new ArrayList<>();
        List<Integer> linkedList = new LinkedList<>();
        for (int i = 0; i < 1000000; ++i) {
            arrayList.add(i);
            linkedList.add(i);
        }
        test1(arrayList);
        test2(arrayList);
        test3(arrayList);

        test1(linkedList);
        test2(linkedList);
        test3(linkedList);
    }
    //for循环测试
    public static void test1(List<Integer> list) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < list.size(); ++i) {
            int num = list.get(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("test1 : " + (end - start));
    }
    //iterator测试
    public static void test2(List<Integer> list) {
        long start = System.currentTimeMillis();
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            int num = (Integer) iterator.next();
        }
        long end = System.currentTimeMillis();
        System.out.println("test2 : " + (end - start));
    }
    //for each测试
    public static void test3(List<Integer> list) {
        long start = System.currentTimeMillis();
        for (Integer integer : list) {
            int num = integer;
        }
        long end = System.currentTimeMillis();
        System.out.println("test3 : " + (end - start));
    }
}

二、ArrayList遍历性能比较(时间单位:微秒)

size 10 100 1,000 10,000 100,000 1,000,000
for循环 0 0 1 2 10 13
Iterator 1 0 0 2 11 14
for each 0 0 0 2 11 12

三、LinkedList遍历性能比较(时间单位:微秒)

size 10 100 1,000 10,000 100,000 1,000,000
for循环 0 0 3 74 8656 >15min
Iterator 1 1 1 2 4 26
for each 0 0 1 3 4 29

四、总结

  1. 对于ArrayList,无论size是多大,耗时都差不多,选择哪种方式都一样
  2. for each内部其实也是用iterator实现的,所以不管是ArrayList还是LinkedList,iterator和for each的性能都差不多
  3. 由于LinkedList每次get的时候,都得从开始位置查找,所以遍历的的性能会很慢
  4. 综合来看,建议用for each,代码简洁,性能也不差

五、参考资料

https://blog.csdn.net/dengnanhua/article/details/64692191

https://blog.csdn.net/xyc_csdn/article/details/69683799

你可能感兴趣的:(Java)