ArrayList 与 LinkedList的插入效率实践分析

ArrayList 与 LinkedList的效率实践分析

我们已知的ArrayList以及LinkedList是如下的一个描述:

ArrayList 底层使用连续空间进行顺序存储,随机查询快O(1),增加和删除慢

LinkedList 底层使用双向队列实现,随机查询较慢,插入速度,删除速度快

但是不经过验证如何说明问题。本文将会对ArrayList和LinkedList的插入、查询、删除进行实验,通过实验得到的数据来说明性能问题

测试机器配置:
CPU: i7 - 6700HQ
内存:16GB

1.ArrayList与LinkedList的极端插入情况

何为极端插入?,我们令一个列表是S[1…n],我们知道ArrayList是顺序存储,每一次插入都需要移动元素,如果我们将数据插入S[1],那么数组将会最大次数的移动元素,会导致内存数据的大批量复制这也是插入的最坏情况。在ArrayList源码中的add(int index,E element)是这样做的

  /**
 * Inserts the specified element at the specified position in this
 * list. Shifts the element currently at that position (if any) and
 * any subsequent elements to the right (adds one to their indices).
 *
 * @param index index at which the specified element is to be inserted
 * @param element element to be inserted
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

而LinkedList采用链表,则不存在移动元素的问题,只是会新建节点并修改相关引用。

   public void add(int index, E element) {
    checkPositionIndex(index);

    if (index == size)
        linkL
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值