本文基于https://juejin.cn/post/6844903728324018189 这个文章又自己测了一下,看了这个文章以前我的认知一直是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");
}
结果
开始插入,LinkedList长度为:100000
开始插入,ArrayList长度为:100000
长度比例:0.025插入完成,LinkedList长度为:200000 耗时:1721ms
长度比例:0.025插入完成,ArrayList长度为:200000 耗时:1834ms
经过多测修改系数测试,也就是说只有在插入的位置是总长度的1/40左右的时候linkedList和arrayList的速度是差不多,之后arrayList的速度都比linkedList快,如果arrayList设置合适的初始长度,避免扩容,速度会更快。
总结 如果没有特殊需求,尽量用arrayList,毕竟查询很快,插入速度在多数情况下不慢,毕竟一般需求插入的位置基本来说是平均分配的。
人懒不喜排版,随便看看吧。