Thursday, November 1, 2007

.NET goodie #1: Declaring variables inside or outside of a loop impact performance?

Did you ever wonder......
Is there any difference in terms of performance between declaring a variable outside of a loop like this...

string str = "";

for (int i = 0; i < 10; i++)

{

str = "hello";
}


...versus declaring the variable within a loop and using it like this:


for (int i = 0; i < 10; i++)

{

string str = "hello";
}

So what do you think???!!! The asnwer in this case will be:

The first example is actually slower, because it causes one more string allocation to occur. In c# the "creation" of variables is always moved to the top of methods in the compiled IL. Therefore your second example is exactly the same performace as:

string str;


for (int i = 0; i < 10; i++)

{

str = "hello";
}


Notice this does not assign an initial value to str of "".

1 comment:

Unknown said...

Its an Awesome written article. After these steps columns can be accessed with indexer operator quite easily.
http://www.dapfor.com/en/net-suite/net-grid/features/performance