Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: List.Count vs checking a stored variable

Tags:

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?

like image 909
Sturm Avatar asked Jun 18 '13 13:06

Sturm


2 Answers

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'

like image 82
Bas Avatar answered Oct 14 '22 17:10

Bas


Well you can look at the .NET Source code here http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs#aa7e01fcb80a917e

  public int Count {
        get {
            Contract.Ensures(Contract.Result<int>() >= 0);
            return _size; 
        }
    }

It would appear that .Count property on list does a quick internal check and then returns _size. So it should be pretty close to the performance of you storing the value yourself.

like image 38
ProVega Avatar answered Oct 14 '22 15:10

ProVega