0

Possible Duplicate:
Difference between declaring variables before or in loop?

I was asked following question in one of my interview. Which loop is more efficient

void Fun()
{
   string strTest = string.Empty;
   for (int i = 0 ; i < 10000; i++ ) 
   {
       strTest = "String : " + i;
       System.Console.WriteLine(strTest);
   }
}

OR

void Fun()
{

   for (int i = 0 ; i < 10000; i++ ) 
   {
       string strTest = string.Empty;
       strTest = "String : " + i;
       System.Console.WriteLine(strTest);
   }
}

I think declaring string outside is more efficient? Am I right?
I was asked why - I told it will create lees overhead on GC.
Please correct me if I am wrong. Regards, Hemant Shelar

Community
  • 1
  • 1
  • 4
    There's no need to set the sting to `string.Empty` if you're going to set it to something else straight afterwards. – ChrisF Mar 12 '12 at 12:44
  • 1
    They both have the same amount of GC overhead. I can't imagine one would be more efficient than the other. – Gabe Mar 12 '12 at 12:45
  • 1
    possible duplicate of [Difference between declaring variables before or in loop?](http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop) and http://stackoverflow.com/questions/1884906/declaring-a-variable-inside-or-outside-an-foreach-loop-which-is-faster-better – Yuck Mar 12 '12 at 12:45
  • Why don't you use `System.Console.WriteLine("String : " + i);` directly ? – Amen Ayach Mar 12 '12 at 12:47

0 Answers0