Thursday, 30 January 2014

What is the difference between declare variable inside or outside the loop in C# ASP.NET

Sometimes user Search these type of questions :-
  • Difference between declaring variables before or in loop
  • Is it better to declare a variable inside a loop
  • Is there is any performance difference between declare a variable outside or inside a loop 
Solution:-

In Short, Performance-wise both cases are compiled to the same IL, so there's no difference.

Let's See Example
Case 1: 
                int num;
                for (int i = 0; i < count; i++) 
                {
                        num = i;
                }


Case 2:
for (int i = 0; i < count; i++) { int num = i; }
 I think only difference between above two cases is, defining variables inside the loop makes it visibility local to that loop only because declaration does not cause any perceivable difference in performance.Personally, I Prefer the second one because it reduces scope of variables to where they are needed, which is good thing. 


That’s it!!…..Happy Programming...

No comments:

Post a Comment