For loop performance question

Hello,

I have a general question regarding performance. I have a class with a method that returns a List. The method that calculates this list is rather complex, so I don’t want it to run more often than necessary.

Is it ok to do something like this:

foreach (Vector2 position in myInstance.GetPositions())
   ....

Or should I do:

List<Vector2> positions = myInstance.GetPositions());
foreach (Vector2 position in positions)
    ....

And what about using a regular for loop, any difference to the above?

for (int i = 0; i < positions.Count; i++)
{
   Vector2 position = positions[i];
   ....
}

The first 2 won’t have much a difference in performance.

The last one will slightly perform better in the long run because it avoid calling the ‘GetEnumerator’ of the List. The ‘foreach’ statement utilizes the IEnuemrable.GetEnumerator method, which returns an interfaced object. This means an allocation on the heap, and a cost for garbage collecting it later.

Note - calling GetEnumerator directly, and while(e.MoveNext()) on it doesn’t suffer this for classes like List, because then you’re calling the version of it that returns a struct, which doesn’t suffer the allocation. It’s not boxed, so no heap allocation.

1 Like

From my experience for each loops are slower than for loops because for each has additional steps it must take to enumerate the object which is placing a few more variables on the stack than the for loop. The performance difference is unnoticeable though and in nanoseconds. I think having your method return a list within the loops declaration would be equivalent both functionally and performance wise.

Alright, thank you both very much for clearing it up!