Reputation: 828
Does the compiler treat the two cases below identically, or does case 2 offer a performance increase because x/2 is not constantly re-evaluated? I have always assumed the latter but it would be great if someone could confirm this.
Case 1:
double result;
for (int i = 0; i < 10000000; i++) {
result += variables[i] * (x/2);
}
return result;
Case 2:
double result;
double xOverTwo = x/2;
for (int i = 0; i < 10000000; i++) {
result += variables[i] * (xOverTwo);
}
return result;
Upvotes: 1
Views: 193
Reputation: 700222
That depends on what x
is.
If it is a constant, then the calculation is done at compile time, so the two codes perform identically. If it is a volatile variable, then the compiler will be forced to do the calculation each time, so then you would definitely benifit from calculating it outside the loop.
For any other case it depends on whether the compiler itself can optimise the code to do the calculation outside the loop or not. To be on the safe side you can calculate the value outside the loop.
Of course, in your example you don't need to use x
inside the loop at all, which would be an example of modifying the method used instead of trying to optimise it:
double result;
for (int i = 0; i < 10000000; i++) {
result += variables[i];
}
return result * (x / 2);
Upvotes: 7