Search code examples
c#performanceloopscount

Performance: List.Count vs checking a stored variable


I wonder if this makes any difference:

 for (int i = 0; i < values.Count; i++)
        {
            //
        }

vs

int num = values.Count;

for(int=0; i<num; i++)
{

}

I think the second approach is better because you don't need to count all the items in each iteration. But I may be wrong. Could someone illuminate me?


Solution

  • The list already stores its Count internally. The comparison you are doing is related to code style, not performance. Since the compiler will optimize the retrieval of 'Count'