1

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;
dtb
  • 213,145
  • 36
  • 401
  • 431
Coder1095
  • 828
  • 10
  • 25
  • 1
    Have you timed these two snippets? Which one (if either) is faster? – ChrisF Nov 10 '12 at 23:39
  • 2
    It is a poor example because it is unverifiable, but this generally falls into "loop hoisting optimization" category, one of the optimizations that the jitter knows how to do. A *very* attractive optimization since the pay-off is big. Documented here: http://stackoverflow.com/questions/4043821/performance-differences-between-debug-and-release-builds/4045073#4045073 – Hans Passant Nov 10 '12 at 23:40

1 Answers1

7

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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005