I'm writing an algorithm which do a big loop over an integer array from the end to the beginning with a if condition inside. At the first time the condition is false the loop can be terminated.
So, with a for loop, if condition is false it continues to iterate with simple variables changes. With a while loop with the condition as while parameter, the loop will stop once condition false and should save some iterations.
However, the while loop remains a little slower than the for loop!
But, if I put a int value as counter, and count iterations, the For loop as expected performed much more iterations. However this time, the time execution of the mofified For method with the counter will be much more slower than the while method with a counter!
Any explanations?
here the code with a for loop:
for (int i = pairs.length - 1; i >= 0; i -= 2) {
//cpt++;
u = pairs[i];
v = pairs[i - 1];
duv = bfsResult.distanceMatrix.getDistance(u, v);
if (duv > delta) {
execute();
}
}
time execution: 6473
time execution with a counter: 8299
iterations counted: 2584401
here the code with the while loop:
int i = pairs.length - 1;
u = pairs[i];
v = pairs[i - 1];
duv = bfsResult.distanceMatrix.getDistance(u, v);
while (duv > delta) {
//cpt++;
execute();
u = pairs[i -= 2];
v = pairs[i - 1];
duv = bfsResult.distanceMatrix.getDistance(u, v);
}
time execution: 6632
time execution with a counter: 7163
iterations counted: 9793
Time is in ms, I repeated the experiment several times with different size intances, the measures remained almost the same. The execute() method updates the delta value. Method getDistance() is just a matrix int[][] access.
Thanks for any help.
duv <= delta.