LinkedList和ArrayList性能比较
LinkedList和ArrayList性能比较
一、样例代码
@Test
public void t6(){
ArrayList<Df> arrayList = Lists.newArrayList();
LinkedList<Df> linkedList = Lists.newLinkedList();
for (int i = 0; i < 500000; i++) {
Df df = new Df().setId(i).setName("n" + i);
arrayList.add(df);
linkedList.add(df);
}
// 遍历操作比较
long x11 = System.currentTimeMillis();
arrayList.stream().map(e -> {
e.setId(e.id + 1);
return e;
}).collect(Collectors.toList());
System.out.println("arrayList 操作单个元素:" + (System.currentTimeMillis() - x11));
long x12 = System.currentTimeMillis();
linkedList.stream().map(e -> {
e.setId(e.id + 1);
return e;
}).collect(Collectors.toList());
System.out.println("LinkedList 操作单个元素:"+(System.currentTimeMillis() - x12));
// 过滤操作比较
long x21 = System.currentTimeMillis();
List<Df> collect1 = arrayList.stream().filter(e -> e.getId() < 60000).collect(Collectors.toList());
System.out.println("arrayList 操作单个元素:" + (System.currentTimeMillis() - x21));
long x22 = System.currentTimeMillis();
List<Df> dfs = linkedList.stream().filter(e -> e.getId() < 60000).collect(Collectors.toList());
System.out.println("LinkedList 操作单个元素:"+(System.currentTimeMillis() - x22));
// 查询单个比较
long x31 = System.currentTimeMillis();
arrayList.get(22222);
System.out.println("arrayList 查询单个:" + (System.currentTimeMillis() - x31));
long x32 = System.currentTimeMillis();
linkedList.get(22222);
System.out.println("LinkedList 查询单个元素:"+(System.currentTimeMillis() - x32));
}
@Data
@Accessors(chain = true)
class Df{
private int id;
private String name;
}
二、测试(基于不同数据量)
2.1、5万数据量
arrayList 遍历修改单条数据67
LinkedList 遍历修改单条数据:13
arrayList 过滤元素:4
LinkedList 过滤元素:4
arrayList 查询单个:0
LinkedList 查询单个元素:1
49999 arrayList 删除数据0
49999 LinkedList 删除数据:0
2.2、50万数据量
arrayList 遍历修改单条数据66
LinkedList 遍历修改单条数据:387
arrayList 过滤元素:11
LinkedList 过滤元素:14
arrayList 查询单个:0
LinkedList 查询单个元素:1
499999 arrayList 删除数据0
499999 LinkedList 删除数据:0
2.3、500万数据量
arrayList 遍历修改单条数据362
LinkedList 遍历修改单条数据:5487
arrayList 过滤元素:62
LinkedList 过滤元素:85
arrayList 查询单个:0
LinkedList 查询单个元素:0
4999999 arrayList 删除数据4
4999999 LinkedList 删除数据:0
三、总结
ArrayList,底层数组,初始容量长度 10,连续的内存空间,默认扩容后 1.5倍
LinkedList,底层链表(指针和节点)