ArrayList与LinkedList都是继承至Collection对象,内部实现导致性能方面存在一定的区别
- 插入性能对比
private final static int COUNT = 10000000; private static long insertObject(List<Object> list) { Object obj = new Object(); long startTime = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { list.add(obj); } long endTime = System.currentTimeMillis(); return endTime - startTime; } public static void main(String[] args) { int initCount = (int) (COUNT * 1.5); System.out.println("ArrayList 增加" + COUNT + "条数据,耗时:" + insertObject(new ArrayList<Object>(initCount))); System.out.println("LinkedList 增加" + COUNT + "条数据,耗时:" + insertObject(new LinkedList<Object>())); }
上述代码得出下列结果:
- 查询性能对比
private final static int COUNT = 1000000;
private static Map<String, Object> insertObject(List<Object> list) {
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) {
user.setId(i);
user.setName("i:" + i);
user.setAge(i);
list.add(user);
}
long endTime = System.currentTimeMillis();
Map result = new HashMap<String, Object>();
result.put("time", endTime - startTime);
result.put("list", list);
return result;
}
private static long readObject(List<User> list) {
long startTime = System.currentTimeMillis();
for (User user : list) {
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static void main(String[] args) {
// 插入
int initCount = (int) (COUNT * 1.5);
Map<String, Object> arrayListResult = insertObject(new ArrayList<Object>());
Map<String, Object> linkedListResult = insertObject(new LinkedList<Object>());
System.out.println("ArrayList 增加" + COUNT + "条数据,耗时:" + arrayListResult.get("time"));
System.out.println("LinkedList 增加" + COUNT + "条数据,耗时:" + linkedListResult.get("time"));
// 读取
System.out.println("ArrayList 查询" + COUNT + "条数据,耗时:" + readObject((List<User>) arrayListResult.get("list")));
System.out.println("LinkedList 查询" + COUNT + "条数据,耗时:" + readObject((List<User>) linkedListResult.get("list")));
}
- 修改性能对比
- 移除性能对比
原文地址:https://blog.51cto.com/11219183/2401485
时间: 2024-10-29 10:46:18