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

通过不同规模的数据填充测试,探讨Java中HashMap的实际负载极限,并对比预设容量的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

按说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

 

转载于:https://www.cnblogs.com/lakeslove/p/7100916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值