Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will declaring a variable inside/outside a loop change the performance?

Tags:

c#

Is this:

foreach(Type item in myCollection)
{
   StringBuilder sb = new StringBuilder();
}

much slower than:

StringBuilder sb = new StringBuilder();

foreach(Type item in myCollection)
{
   sb = new StringBuilder();
}

In other words, will it really matter where I declare my StringBuilder?

like image 885
Rod Avatar asked Aug 02 '10 14:08

Rod


Video Answer


2 Answers

No, it will not matter performance-wise where you declare it.

For general code-cleanliness, you should declare it in the inner-most scope that it is used - ie. your first example.

like image 184
Blorgbeard Avatar answered Oct 16 '22 09:10

Blorgbeard


You could maybe gain some performance, if you write this:

StringBuilder sb = new StringBuilder();
foreach(Type item in myCollection)
{
   sb.Length = 0;
}

So you have to instantiate the StringBuilder just once and reset the size in the loop, which should be slightly faster than instantiating a new object.

like image 42
Scoregraphic Avatar answered Oct 16 '22 09:10

Scoregraphic