首页 > 代码库 > HashMap存入大量数据是否要预定义存储空间

HashMap存入大量数据是否要预定义存储空间

按说HashMap的负载极限为0.75,可是,测试程序并看不出这个结果。待探讨

测试程序如下:

根据结果看不出来预定义有什么影响。

public class test {
    public static void main(String[] args) {
        testRun(5000000);
        testRun(10000000);
        testRun(15000000);
        testRun(20000000);
        testRun(25000000);
        testRun(30000000);
        testRun(35000000);
        testRun(40000000);
        testRun(45000000);
        testRun(50000000);
         
    }
    public static void testRun(int mapCount){
        System.out.println("============"+mapCount+"=============");
        run(mapCount,new HashMap<>());
        run(mapCount,new HashMap<>(mapCount));
        run(mapCount,new HashMap<>((int)(mapCount/0.75)));
        run(mapCount,new HashMap<>((int)(mapCount/0.6)));
        run(mapCount,new HashMap<>((int)(mapCount/0.5)));
        
    }
    
    public static void run(int mapCount,Map<Integer,String> testMap){
         String testValue = "";
         Long startTime0 = System.currentTimeMillis();
         for(int i = 1;i<mapCount;i++){
             testMap.put(i, testValue);
         }
         Long endTime0 = System.currentTimeMillis();
         System.out.println(endTime0-startTime0);
    }
}
============5000000=============
1670
689
981
260
211
============10000000=============
1097
4485
793
386
331
============15000000=============
768
3394
2805
5651
6022
============20000000=============
8155
2153
5089
6078
6809
============25000000=============
8890
6998
10050
9149
10501
============30000000=============
14467
10527
9334
11453
13733
============35000000=============
14493
11978
13706
13809
11461
============40000000=============
15788
13439
18142
13514
11351
============45000000=============
12952
18501
17793
11894
30664
============50000000=============
29528
14534
14272
32803
42236

 

HashMap存入大量数据是否要预定义存储空间