我已经尝试构建自己的Map以提高特殊环境的性能,并且我意识到一些非常有趣的事情:创建一个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 …Run Code Online (Sandbox Code Playgroud)