简体   繁体   English

While循环比for循环更有效。 可能是什么原因?

[英]While loop is more efficient than for loop. What could be the reason?

I was doing a LeetCode challenge ( here ) for fun and was surprised that the while loop was more efficient than the for loop. 我正在( 这里 )进行LeetCode挑战,很有趣,而while循环比for循环更有效。 I would have expected the compiler to generate identical code (also as per these question and answers ), but the run times are different. 我本来希望编译器生成相同的代码(也根据这些问题和答案 ),但是运行时间不同。

The while loop was around 3 ms, whilst the for loop took around 6ms. while循环大约3毫秒,而for循环大约6毫秒。 I repeated a couple of times and it seemd to be often like that. 我重复了几次,似乎经常是这样。

I don't have the test cases unfortunately, and I don't have any information about compiler used, the architecture or optimizations set. 不幸的是,我没有测试用例,也没有有关使用的编译器,体系结构或优化设置的任何信息。 I think it is not important because the programs are almost identical and use the same compiler, architecture and options surely. 我认为这并不重要,因为程序几乎相同,并且肯定使用相同的编译器,体系结构和选项。

Any ideas or experiences in that matter ? 有什么想法或经验吗?

For loop: 对于循环:

vector<int> twoSum(vector<int>& numbers, int target) {
    int upper = numbers.size() - 1;
    int lower = 0;
    int sum;

    for (;lower<upper;) {
        sum = numbers[lower] + numbers[upper];
        if (sum == target) {
            return vector<int> { lower+1, upper+1 };
        } else if (sum > target) {
            upper--;
        } else {
            lower++;
        }
    }
}

While loop: While循环:

vector<int> twoSum(vector<int>& numbers, int target) {
    int upper = numbers.size() - 1;
    int lower = 0;
    int sum;

    while (lower<upper) {
        sum = numbers[lower] + numbers[upper];
        if (sum == target) {
            return vector<int> { lower+1, upper+1 };
        } else if (sum > target) {
            upper--;
        } else {
            lower++;
        }
    }
}

You did not run enough or long enough tests, benchmarks in milliseconds is hard to verify. 您没有运行足够或足够长时间的测试,很难验证以毫秒为单位的基准。

A better way is to compare the generated assembly: for-loop and while-loop . 更好的方法是比较生成的程序集: for-loopwhile-loop The snippets are compiled with maximum optimization ( -O3 ), using g++ 6.3. 使用g ++ 6.3以最大的优化( -O3 )编译代码片段。 From this it is clear that there is no performance difference at all, since the assembly for the two is exactly the same. 由此可见,由于两者的组装完全相同,因此根本没有性能差异。

All loops follow the same template: 所有循环都遵循相同的模板:

{
// Initialize
LOOP: 
if(!(/* Condition */) ) {
    goto END
}

// Loop body

// Loop increment/decrement
goto LOOP
}
END:

Your test must have differed by the available processing power on your CPU. 您的测试必须因CPU上的可用处理能力而异。

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

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