0

Declare variables in an inner scope is what I see everywhere! but I have a question: Let's say we have a for-loop and we want to use a variable inside the body of that loop. Well if I declare and initialize the variable in the inner scope which is inside the loop, won't it have more overhead because every time that the loop runs that variable should be declared again? I am using C#, so if there are compiler optimizations about this, even better.

Bohn
  • 26,091
  • 61
  • 167
  • 254
  • http://stackoverflow.com/questions/1985760/how-does-the-c-sharp-compiler-optimize-a-code-fragment – Alex Apr 20 '12 at 17:56
  • possible duplicate of [Difference between declaring variables before or in loop?](http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop) – Dan J Apr 20 '12 at 18:03
  • I don't agree with the answers to those questions! more followup: http://stackoverflow.com/questions/10251432/declare-the-varible-closer-to-where-it-is-defined-c-sharp-il-code-is-not-the-sa – Bohn Apr 20 '12 at 18:21

1 Answers1

1

Well it depends on the compiler. In C# compiler will optimize it and you will not see any significant difference. The good thing about declaring variable inside the loop is that when it goes out of loop (out of scope) it is available for garbage collection. Also check out this thread Difference between declaring variables before or in loop?

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • more followup: http://stackoverflow.com/questions/10251432/declare-the-varible-closer-to-where-it-is-defined-c-sharp-il-code-is-not-the-sa – Bohn Apr 20 '12 at 18:20