增强for循环

增强for循环对性能的影响–基于leetcode中常用的对数组遍历

​ 在leetcode刷题中,常遇到要是用for循环对数组进行遍历,

// for循环主要有以下两种写法
for (int i = 0; i < nums.length; i++) {}
for (int i : nums) {}

​ 本以为以上两种方法应该差别不大,但在一道很简单的leetcode题目中,出现了较大的性能差异。

​ 题目链接:求出出现两次的数字的XOR值

// 写法一:
class Solution {
    public int duplicateNumbersXOR(int[] nums) {
        if (nums.length <= 1) {
            return 0;
        }
        int res = 0;
        HashSet<Integer> appearedNums = new HashSet<>();
        for (int i : nums) {
            if (appearedNums.contains(i)) {
                res = res ^ i;
            } else {
                appearedNums.add(i);
            }
        }
        return res;
    }
}
// 写法二:
class Solution {
    public int duplicateNumbersXOR(int[] nums) {
        if (nums.length <= 1) {
            return 0;
        }
        int res = 0;
        HashSet<Integer> appearedNums = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (appearedNums.contains(nums[i])) {
                res = res ^ nums[i];
            } else {
                appearedNums.add(nums[i]);
            }
        }
        return res;
    }
}

其实两者主要就差在对nums[i]的访问上,对于增强for循环,尽管代码中没有显式的索引变量,编译器会将它转换成如下的等价代码:

for (int i = 0; i < nums.length; i++) {
  int num = nums[i];
  // 继续下面操作...
}

虽然使用增强for循环,但是对于set、map、list等集合类,未必会性能优异?,后续会继续探讨。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值