我尝试构建自己的地图以提高特定环境下的性能,并且发现了一些有趣的事情:创建一个 new Hashmap<Integer,String>(2000)
比 new Object[2000]
快—无论我以什么顺序执行这些命令。这对我来说非常令人困惑,特别是因为 Hashmap 构造函数包含一个 table = new Entry[capacity]
,根据这里。我的测试台有什么问题吗?
public static void test(int amm){ //amm=1_000_000
Map<Integer,String> m1 = null;
Object[] arr = null;
long time = System.nanoTime();
for(int i = 0; i < amm; i++){
m1 = new HashMap<Integer, String>(2000);
}
System.out.println("m1: " + (System.nanoTime() - time)); //m1: 70_455_065
time = System.nanoTime();
for(int i = 0; i < amm; i++){
arr = new Object[2000];
}
System.out.println("arr: " + (System.nanoTime() - time)); //arr: 1_322_473_803
}
我希望能在另一台电脑上看到测试结果。我不知道为什么创建一个HashMap
比创建一个Object[]
快10倍。