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++;
}
}
}