JDK 8源码解析——ArrayList和LinkedList迭代性能比较

我们都知道查询用ArrayList,插入用LinkedList,原因在于ArrayList内部数据用数组的形式进行组织,但是LinkedList用链表的形式进行组织。因此ArrayList查询有优势,LinkedList插入有优势。那么在迭代的情况下, ArrayList和LinkedList的有多大的差别呢?先上代码。

public class App
{
    private static final int MAX_LENGTH = 10 * 10000;
    
    public static void main(String[] args)
    {
        List<Integer> arrayList = getRandomArray();
        List<Integer> linkedList = new LinkedList(arrayList);
        System.out.println("This is begin, array size is " + MAX_LENGTH);
        forArray(arrayList);
        forArray(linkedList);
        System.out.println("========================================================");
        iteratorArray(arrayList);
        iteratorArray(linkedList);
    }
    
    /**
     * 获取一个随机数组
     */
    private static List<Integer> getRandomArray()
    {
        List<Integer> randomArray = new ArrayList<>();
        for (int i = 0; i < MAX_LENGTH; i++)
        {
            randomArray.add(Double.valueOf(Math.random() * 10).intValue());
        }
        return randomArray;
    }
    
    /**
     * 利用for进行循环
     */
    private static void forArray(List<Integer> list)
    {
        long startTime = System.currentTimeMillis();
        int sum = 0;
        for (int i = 0; i < MAX_LENGTH; i++)
        {
            sum += list.get(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println(list.getClass().getSimpleName() + " for loop spend time: " + (endTime - startTime) + "ms"
            + ", this sum is " + sum);
    }
    
    /**
     * 利用迭代器进行循环
     */
    private static void iteratorArray(List<Integer> list)
    {
        Iterator<Integer> iterator = list.iterator();
        long startTime = System.currentTimeMillis();
        int sum = 0;
        while (iterator.hasNext())
        {
            sum += iterator.next();
        }
        long endTime = System.currentTimeMillis();
        System.out.println(list.getClass().getSimpleName() + " iterator spend time: " + (endTime - startTime) + "ms"
            + ", this sum is " + sum);
    }
}

创建10w大小的数组,进行迭代实验。

第1次迭代:

第2次迭代:

第3次迭代:

通过观察以上数据,其实有个非常扎眼的数据,就是使用for循环时,LinkedList的效率也太低了吧,因为即使访问数组的效率高于引用方法,但是这种跨越几个数量级的差别还是值得引起重视的。再加上ArrayList和LinkedList的迭代器分别用数组和链表实现,但是他们的执行效率反而是LinkedList更高。

其实关键点在于get方法的实现。通过阅读源码,发现ArrayList实现get方法时间复杂度为O(1)

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

但是 LinkedList实现get方法的时间复杂度为O(n)

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

因此使用for循环进行迭代时,LinkedList的执行效率很低,如果换用迭代器,则会提升很高的效率。

通过这个实验,也让我明白了,并不是数组就要比链表迭代快,而是在于查询的时间复杂度的差别。所以,算法很重要啊。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值