Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

For loop performance question

Discussion in 'Scripting' started by CG_Echtzeitschmiede, Nov 28, 2015.

  1. CG_Echtzeitschmiede

    CG_Echtzeitschmiede

    Joined:
    Feb 19, 2015
    Posts:
    93
    Hello,

    I have a general question regarding performance. I have a class with a method that returns a List<Vector2>. 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:
    Code (CSharp):
    1. foreach (Vector2 position in myInstance.GetPositions())
    2.    ....
    Or should I do:
    Code (CSharp):
    1. List<Vector2> positions = myInstance.GetPositions());
    2. foreach (Vector2 position in positions)
    3.     ....
    And what about using a regular for loop, any difference to the above?
    Code (CSharp):
    1. for (int i = 0; i < positions.Count; i++)
    2. {
    3.    Vector2 position = positions[i];
    4.    ....
    5. }
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,514
    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.
     
    Magnumstar likes this.
  3. Magnumstar

    Magnumstar

    Joined:
    Oct 3, 2015
    Posts:
    304
    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.
     
  4. CG_Echtzeitschmiede

    CG_Echtzeitschmiede

    Joined:
    Feb 19, 2015
    Posts:
    93
    Alright, thank you both very much for clearing it up!