Java中while和for循环性能比较

本文通过代码示例对比了Java中while和for循环在填充HashMap时的性能。程序创建了一个1000x1000的HashMap,并记录了两种循环方式所消耗的时间。结果显示,两种循环方式在实际运行时的性能差异可能并不显著,主要取决于JVM的优化和具体环境。
摘要由CSDN通过智能技术生成

Java中while和for循环性能比较

public static void main(String[] args) {
   

```java
 long startTime = System.currentTimeMillis();
    Map<String, Map<String, String>> map = new HashMap<>();
    int i = 0;
    int j = 0;
    while (i < 1000) {
        while (j < 1000) {
            Map<String, String> mapVal = new HashMap<>();
            mapVal.put("addressTypeID", Math.random() * 5 + "");
            mapVal.put("dataTypeNum", Math.random() * 5 + "");
            mapVal.put("variableAddress", Math.random() * 5 + "");
            mapVal.put("memoryType", Math.random() * 5 + "");
            mapVal.put("deviation", Math.random() * 5 + "");
            mapVal.put("variableID", Math.random() * 5 + "");
            mapVal.put("val", Math.random() * 5 + "");
            map.put(j + "", mapVal);
            j++;
        }
        i++;
    }
    long endTime = System.currentTimeMillis();
    System.out.println(endTime - startTime + "mm:while");
    long startTime1 = System.currentTimeMillis();
    Map<String, Map<String, String>> map1 = new HashMap<>();
    for (int k = 0; k < 1000; k++) {
        for (int l = 0; l < 1000; l++) {
            Map<String, String> mapVal = new HashMap<>();
            mapVal.put("addressTypeID", Math.random() * 5 + "");
            mapVal.put("dataTypeNum", Math.random() * 5 + "");
            mapVal.put("variableAddress", Math.random() * 5 + "");
            mapVal.put("memoryType", Math.random() * 5 + "");
            mapVal.put("deviation", Math.random() * 5 + "");
            mapVal.put("variableID", Math.random() * 5 + "");
            mapVal.put("val", Math.random() * 5 + "");
            map1.put(j + "", mapVal);
        }
    }
    long endTime1 = System.currentTimeMillis();
    System.out.println(endTime1 - startTime1 + "mm:for");

}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210412142422302.png#pic_center)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lanerwang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值