Can a VS2010 C++/C# compiler optimize away variables declared inside of the loop? -


i pretty new @ place, should think twice before voicing concerns, of code have seen ...

when try bring readability, told there not time that, efficiency far more important.

but see variable redeclaration inside of different types of loops, down 2 levels. part of me thinks - not ever that! other part says - complicated function should broken down several functions anyway. smaller functions can have temp variables, , compiler should able take care of them.

then function calls add additional cost it. let me try come 2 examples:

class1::do1() {     (int = 0; < 100; i++)     {         bool x = getsomevalue();         ...         if (x)         {             ...         }     }  } 

vs

class1::do1() {     bool x = false;     (int = 0; < 100; i++)     {         x = getsomevalue();         ...         if (x)         {             ...         }     }  } 

vs

class1::do1() {     (int = 0; < 100; i++)     {         do2();     }  }  class1::do2() {     bool x = getsomevalue();     ...     if (x)     {         ...     } } 

the first way looks wrong me, prefer second or third when write code myself. think third way might slower due function calls. first way might sketchy @ times - in case function long, declaration number of lines away used. other thing example simple - compiler figure out how simplify, , perhaps inline 3. unfortunately right cannot recall other examples of think sloppiness, want mention variables redeclared n*m times, because 2 levels deep (within 2 loops).

the devil's advocate says - how know 100% might not efficient? purist (my version of it) in me thinks stupid redeclare same variable on , on , on - @ least throws 1 off when reading code.

thoughts? questions?

as far recall local variables assigned stack space @ beginning of method call, should not matter whether declare variable within loop or before it.

that being case code readability - if don't need variable outside loop declare in loop, keep closer code uses , reducing scope of variable as possible.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -