0

if i have a for loop for example and and i want to use something like Math.round() to round the number but i only need to round the number one time(i.e the number doesn't change throughout the loop) is it better to store it into a variable and then use the variable to in the condition or does it not matter?

 for (int i = 0;i < Math.Round(x);i++)
   {
   //Some code  
   }

vs

 for (int i = 0,roundedX = Math.Round(X); i<roundedX;i++)
  {  
  //Some code 
  }
SuperMinefudge
  • 301
  • 3
  • 11

2 Answers2

8

The compiler will evaluate the termination condition on every loop iteration.

The compiler and the JITter might hoist some expression or part of an expression outside the loop if it deems it is invariant, meaning it doesn't change. This, however, is usually only done with simpler expressions.

If the Math.Round(X) expression could've been done without an actual method call then perhaps but in this particular case the rounding will happen on each loop iteration.

As such, if you're at last line defense for performance problems, you might consider moving this out and into a variable:

int goal = (int)Math.Round(X);
for (int i = 0; i < goal; i++)
    ...

As this will call the Math.Round method only once, you only get the performance hit once.

Note that if X changes as part of the loop, then obviously you want to keep your original code.

Ben
  • 34,935
  • 6
  • 74
  • 113
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • 2
    I say "Performance hit" but most likely this will do very little or nothing to your performance. Unless you're doing very small workloads inside the loop, and have a very high end value, I would probably not bother with this. – Lasse V. Karlsen Jun 05 '17 at 12:55
  • It could be worthwhile for some Math methods - particularly if they are quite slow (e.g. https://stackoverflow.com/questions/447282/why-is-math-divrem-so-inefficient ). – mjwills Jun 05 '17 at 13:12
2

I would suggest defining a variable

 var roundedX = Math.Round(X);
 for (int i = 0; i < roundedX; i++)
 {  
    //Some code 
 }
Ivan Mladenov
  • 1,787
  • 12
  • 16