3

Possible Duplicates:
for loop optimization
for-loop optimization - needed or not?

e.g.

  int maxloop = complicated();
   for (int i=0;i<maxloop;i++){}

or

 for (int i=0;i<complicated();i++){}

Is the compiler smart enough to optimize it?

what about while?

Community
  • 1
  • 1
colinfang
  • 20,909
  • 19
  • 90
  • 173

4 Answers4

2

No, the compiler is not smart enough to optimize it because it cannot guarantee that complicated() doesn't do anything different if it is run multiple times.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
1

Actually you need to assign the output to a variable to avoid the recalculation overhead. Compiler doesn't do this because you may have an aim in putting a method return value as the limit (i.e. you may need to recalculate the limit after each iteration). To test this, just put Thread.Sleep(5000); in the compilcated() method and you'll see the wait time.

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
0

No, it isn't, as complicated could be a method depending on other complex methods or result in different behaviour after each iteration.

Femaref
  • 60,705
  • 7
  • 138
  • 176
0

The compiler cannot optimize it because there are situations in which "complicated()" will not return the same integer every time. Therefore, the condition is executed every time. Your first snippet of code is must more efficient.

Chris
  • 1,569
  • 2
  • 11
  • 18