3
Answers

Efficiencies of loops

Micah Martin

Micah Martin

17y
2k
1

I had a long debate last night about the effeciences of for loops, for each loops, and the instantiation of variables. Take a look at the following loops:

//Loop #1
MyObject
obj = null;
for (int i = 0; i < myObjectCollection.Count; i++)

   obj = myObjectCollection.Count[i];
   //Do something with obj...
}

OR

//Loop #2
for (int i = 0; i < myObjectCollection.Count; i++)

   MyObject obj = myObjectCollection.Count[i];
   //Do something with obj...
}

Essentially both of these loops do the same thing. However I have a few questions:

1) In loop #2 it appears that "obj" gets instantiated each time through the loop therefore allocating a new location in the stack. Is this correct or does the compiler optimize this to allow the variable to remain in the same location each time just passing it a new reference to the object in the collection?

2) In either loop is it necessary/more effecient to set "obj = null" at any point to speed up garbage collection?

3) In general which of these is more effecient and why?

Thanks,

Micah Martin

Answers (3)