Alex Rivera | Logout

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

Asked 2010-08-02T14:10:26.027
11

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?

c#
Edit
Report

1 Answer

2

In the 2nd example you're creating an extra instance of StringBuilder. Apart from that they are both they same, so the performance issue is negligable.

answered 2010-08-02T14:13:22.760

Your Answer