增,找,删,性能对比
public class Test {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
List<Cat> list = new ArrayList<>();
List<Cat> remove = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
list.add(new Cat("huahua" + i));
}
long endTime = System.currentTimeMillis();
System.out.println("list add 耗时" + (endTime - startTime) + " 毫秒");
System.out.println("----------------------");
// 打乱heros中元素的顺序
Collections.shuffle(list);
startTime = System.currentTimeMillis();
for (Cat cat : list) {
if (cat.name.equals("huahua" + 150000)) {
endTime = System.currentTimeMillis();
System.out.println("list find 耗时" + (endTime - startTime) + " 毫秒");
}
}
System.out.println("----------------------");
startTime = System.currentTimeMillis();
for (Cat cat : list) {
if (cat.name.equals("huahua" + 150000)) {
remove.remove(cat);
}
}
list.remove(remove);
endTime = System.currentTimeMillis();
System.out.println("list remove 耗时" + (endTime - startTime) + " 毫秒");
System.out.println("----------------------");
startTime = System.currentTimeMillis();
HashMap<String, Cat> heroMap = new HashMap<String, Cat>();
for (int j = 0; j < 1000000; j++) {
Cat cat = new Cat("huahua" + j);
heroMap.put(cat.name, cat);
}
endTime = System.currentTimeMillis();
System.out.println("map put 耗时" + (endTime - startTime) + " 毫秒");
System.out.println("----------------------");
startTime = System.currentTimeMillis();
heroMap.get("huahua" + 150000);
endTime = System.currentTimeMillis();
System.out.println("map find 耗时" + (endTime - startTime) + " 毫秒");
System.out.println("----------------------");
startTime = System.currentTimeMillis();
heroMap.remove("huahua" + 150000);
endTime = System.currentTimeMillis();
System.out.println("map move 耗时" + (endTime - startTime) + " 毫秒");
}
static class Cat {
private String name;
public Cat(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
结果:
list add 耗时372 毫秒
----------------------
list find 耗时89 毫秒
----------------------
list remove 耗时268 毫秒
----------------------
map put 耗时767 毫秒
----------------------
map find 耗时0 毫秒
----------------------
map move 耗时0 毫秒
结论: List 在存数据上比Map快很多,找数据和删除数据比Map慢很多.
网友评论