Reputation: 11152
I was doing a LeetCode challenge (here) for fun and was surprised that the while loop was more efficient than the for loop. 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. 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:
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++;
}
}
}
Upvotes: 1
Views: 587
Reputation: 7017
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.
The snippets are compiled with maximum optimization (-O3
), using g++ 6.3.
From this it is clear that there is no performance difference at all, since the assembly for the two is exactly the same.
Upvotes: 3
Reputation: 630
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.
Upvotes: 0