LinkedList真的是查找慢增删快?

本文基于https://juejin.im/post/5c00987de51d451aa843b67b 这个文章又本身测了一下,看了这个文章之前个人认知一直是linkedList增删快,查询慢,arrayList查询快增删慢,虽然这个文章对于插入的位置比较极端,可是也算是颠覆认知了,文章中对于开头和结尾插入快慢的缘由已经经过源码分析的很透彻了,对于中间插入的测试可能不太好经过数据结构来讲明,因而乎我本身写了个测试方法测试了一波,代码和结果以下,若是不对欢迎指正,轻喷,别骂全家 代码数组

/**
     *
     * @param count 数组长度
     * @param index 插入位置比例
     */
    public static void testInsert(int count, double index) {
        LinkedList testLinkedList = new LinkedList();
        ArrayList testArrayList = new ArrayList();
        for (int i = 0; i < count; i++) {
            testLinkedList.add(7);
            testArrayList.add(7);
        }
        System.out.println("开始插入,LinkedList长度为:" + testLinkedList.size());
        System.out.println("开始插入,ArrayList长度为:" + testArrayList.size());
        long linkedMidBegin = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            int coefficientIndex = (int)(testLinkedList.size() * index);
            testLinkedList.add(coefficientIndex, 7);
        }
        long linkedMidEnd = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            int coefficientIndex = (int)(testArrayList.size() * index);
            testArrayList.add(coefficientIndex, 7);
        }
        long arrayMidEnd = System.currentTimeMillis();
        System.out.println("长度比例:" + index + "插入完成,LinkedList长度为:" + testLinkedList.size() + " 耗时:" + (linkedMidEnd - linkedMidBegin) + "ms");
        System.out.println("长度比例:" + index + "插入完成,ArrayList长度为:" + testArrayList.size() + " 耗时:" + (arrayMidEnd - linkedMidEnd) + "ms");
    }
复制代码

结果bash

开始插入,LinkedList长度为:100000
开始插入,ArrayList长度为:100000
长度比例:0.025插入完成,LinkedList长度为:200000  耗时:1721ms
长度比例:0.025插入完成,ArrayList长度为:200000  耗时:1834ms
复制代码

通过多测修改系数测试,也就是说只有在插入的位置是总长度的1/40左右的时候linkedList和arrayList的速度是差很少,以后arrayList的速度都比linkedList快,若是arrayList设置合适的初始长度,避免扩容,速度会更快。数据结构

总结 若是没有特殊需求,尽可能用arrayList,毕竟查询很快,插入速度在多数状况下不慢,毕竟通常需求插入的位置基原本说是平均分配的。源码分析

人懒不喜排版,随便看看吧。post

相关文章
相关标签/搜索