简体   繁体   English

for循环和if-else语句中的代码

[英]Code in for-loops vs if-else statements

I was trying to solve this problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/ 我试图解决这个问题: https//leetcode.com/problems/longest-substring-without-repeating-characters/

The following code passed all tests in 44 ms. 以下代码在44毫秒内通过了所有测试。

    for (int i = 0; i < s.length(); i++){
        if (!mp.containsKey(s.charAt(i))){
            mp.put(s.charAt(i), i);
            //max = Math.max(max, i-first+1);
        }
        else {
            if (mp.get(s.charAt(i))+1>=first){
                first = mp.get(s.charAt(i))+1;
            }
            mp.put(s.charAt(i), i);
            //max = Math.max(max, i-first+1);
        }
        max = Math.max(max, i-first+1);
    }

But the following code passed all tests in only 20 ms. 但是以下代码仅在20毫秒内通过了所有测试。

    for (int i = 0; i < s.length(); i++){
        if (!mp.containsKey(s.charAt(i))){
            mp.put(s.charAt(i), i);
            max = Math.max(max, i-first+1);
        }
        else {
            if (mp.get(s.charAt(i))+1>=first){
                first = mp.get(s.charAt(i))+1;
            }
            mp.put(s.charAt(i), i);
            max = Math.max(max, i-first+1);
        }
    }

Why is there such a significant difference? 为什么会有这么大的差异? The max value is changed only once in both of the samples but changing it in the if-else statements is far more efficient than changing it at the end of the for loop. 两个样本中的最大值只更改一次,但在if-else语句中更改它的效率远远高于在for循环结束时更改它的效率。 Is this an exception or should we follow this standard whenever coding? 这是一个例外还是我们应该在编码时遵循这个标准?

On simplifying (not early optimizing, see max!) one gets 在简化(不早期优化,请参见最大!)时,我会得到

for (int i = 0; i < s.length(); i++) {
    char ch = s.charAt(i);
    Integer n = mp.get(ch):
    if (n != null) {
        first = Math.max(first, n + 1);
    }
    mp.put(ch, i);
    max = Math.max(max, i - first + 1);
}

Remark the double put of value i in the original version. 备注原始版本中i的双重放置。 If the first Math.max is replaced with an if, the code might be faster. 如果第一个Math.max被替换为if,则代码可能更快。

It is hard to make a statement wrt to speed here for the two original versions, maybe the hotspot compiler saw the redundancy. 对于两个原始版本来说,很难在这里加速声明,也许热点编译器看到了冗余。 Or whatever. 管他呢。

It would be nice seeing a java 8 version, using mp.putIfAbsent or such, but that might meke it slower. 看到一个使用mp.putIfAbsent等的java 8版本会很不错,但这可能会让它变得更慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM