private final static int COUNT = 10000000;
private static long insertObject(List
上述代码得出下列结果:
查询性能对比
private final static int COUNT = 1000000;
private static Map insertObject(List 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();
result.put("time", endTime - startTime);
result.put("list", list);
return result;
}
private static long readObject(List 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 arrayListResult = insertObject(new ArrayList());
Map linkedListResult = insertObject(new LinkedList());
System.out.println("ArrayList 增加" + COUNT + "条数据,耗时:" + arrayListResult.get("time"));
System.out.println("LinkedList 增加" + COUNT + "条数据,耗时:" + linkedListResult.get("time"));
// 读取
System.out.println("ArrayList 查询" + COUNT + "条数据,耗时:" + readObject((List) arrayListResult.get("list")));
System.out.println("LinkedList 查询" + COUNT + "条数据,耗时:" + readObject((List) linkedListResult.get("list")));
}
结果如下所示:
3.LinkedList的优势
static final int N = 500000;
static long timeList(List list) {
long start = System.currentTimeMillis();
Object o = new Object();
for (int i = 0; i < N; i++) {
list.add(0, o);
}
long endTime = System.currentTimeMillis();
return endTime - start;
}
static long readList(List list) {
long start = System.currentTimeMillis();
for (int i = 0, j = list.size(); i < j; i++) {
}
return System.currentTimeMillis() - start;
}
static List addList(List list) {
Object o = new Object();
for (int i = 0; i < N; i++) {
list.add(0, o);
}
return list;
}
public static void main(String[] args) {
System.out.println("ArrayList添加" + N + "条耗时:" + timeList(new ArrayList()));
System.out.println("LinkedList添加" + N + "条耗时:" + timeList(new LinkedList()));
List list1 = addList(new ArrayList<>());
List list2 = addList(new LinkedList<>());
System.out.println("ArrayList查找" + N + "条耗时:" + readList(list1));
System.out.println("LinkedList查找" + N + "条耗时:" + readList(list2));
}