Wednesday, July 31, 2013

Performance difference of inner-scoped variables and outer-scoped

Hi,


I would like to confirm whether my thinking is correct. With the following code block:



public SomeMethod()
{
MyClass myClass = null;
for (int i =0; i < 10; i++)
{
myClass = InstantiateMyClass();
myClass.DoSomething();
}
}



Has any performance/memory advantage over:



public SomeMethod()
{
for (int i =0; i < 10;i++)
{
MyClass myClass = InstantiateMyClass();
myClass.DoSomething();
}
}



In this case, myClass is not immutable. My Thinking is that they are not different because even though you are creating a new variable in the second code block, the first code block also creates the same new memory-space allocation but just re-points an existing variable declaration to a new memory allocation. I've been in conversation with some colleagues who believe that the first code block should be faster.


Anyway...just something to think about over coffee, but your input would be much appreciated.


Kind Regards


Mike



No comments:

Post a Comment