Map创建的时候,宜设置初始化容量。
Map创建的时候,宜设置初始化容量。
package com.kris;
import java.util.HashMap;
import java.util.Map;
public class Maps {
public static void main(String[] args) {
try {
Map<Integer, Integer> map = new HashMap<>();
long s1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
map.put(i, i);
}
long s2 = System.currentTimeMillis();
System.out.println(" 未初始化容量,耗时 : " + (s2 - s1));
Map<Integer, Integer> map1 = newHashMapWithExpectedSize(5000000);
long s5 = System.currentTimeMillis();
for (int i = 0; i < 5000000; i++) {
map1.put(i, i);
}
long s6 = System.currentTimeMillis();
System.out.println(" 初始化容量 5000000,耗时 : " + (s6 - s5));
Map<Integer, Integer> map2 = newHashMapWithExpectedSize(10000000);
long s3 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
map2.put(i, i);
}
long s4 = System.currentTimeMillis();
System.out.println(" 初始化容量 10000000,耗时 : " + (s4 - s3));
}catch (Exception e){
e.printStackTrace();
}
}
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) throws Exception{
return new HashMap(capacity(expectedSize));
}
static int capacity(int expectedSize) throws Exception{
if (expectedSize < 3) {
if (expectedSize < 0){
throw new Exception("容量大小不能初始化为负数");
}
return expectedSize + 1;
} else {
return expectedSize < 1073741824 ? (int)((float)expectedSize / 0.75F + 1.0F) : 2147483647;
}
}
}
运行结果打印
未初始化容量,耗时 : 6499 初始化容量 5000000,耗时 : 1651 初始化容量 10000000,耗时 : 4053 Process finished with exit code 0

浙公网安备 33010602011771号