1

Is there any practical difference (speed, memory) between these two ways of declaring (introducing) variables? Which one is the better way?

Example 1:

for (int i = 0; i < myObjects.Length; i++)
{
    MyObject m = myObjects[i];
}

Example 2:

MyObject m = null;

for (int i = 0; i < myObjects.Length; i++)
{
    m = myObjects[i];
}

Thanks.

  • 1
    If you are going to use object inside for loop only its good to have it in for only. http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop – Nitin Varpe Dec 09 '13 at 05:35
  • Sorry, I should searched the previous questions more. This seems to be already answered in an earlier case. – user3057255 Dec 09 '13 at 07:15

2 Answers2

1

Performance-wise both are compiled to the same IL, so there's no difference.

The first one is better because you are meaning to have a new object in each iteration. Also there is no need to have an object if the loop condition fails

Linga
  • 10,379
  • 10
  • 52
  • 104
1

Example 1 makes it so that m is only "alive", in memory, within the scope of the for loop.

Example 2 makes it so that m stays occupying memory after the for loop finishes executing.

I would go with example 1, this is why: Declaring variables inside or outside of a loop (I won't really tell you, in detail, to force you to read the link.)

Community
  • 1
  • 1