Search code examples
c#ienumerable

Why does List<T>'s MoveNext() implementation use a localList?


I read the implementation for MoveNext() in List<T>:

public bool MoveNext() {
    List<T> localList = list;
 
    if (version == localList._version && ((uint)index < (uint)localList._size)) 
    {                                                     
        current = localList._items[index];                    
        index++;
        return true;
    }
    return MoveNextRare();
}

What is the point of copying the reference to list into the local var localList?

If they are both pointing to the same object, why can't you replace all instances of localList with list?


Solution

  • Probably that is a performance issue. Access to local variables is slightly faster than access to instance variables. And - as List is probably one of the most used classes in the CLR - having good performance matters.

    Local variables can directly be read from stack or maybe a register, while instance variables read the address of the object, and then get the value relative to that.