Reputation: 4125
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?
Upvotes: 21
Views: 11552
Reputation: 196
I tried it both ways, and using "int num=values.Count;" won by a large margin. My test used Performance Analyzer and ran the approaches back to back. Then I switched which one runs first, and again storing it to an integer won. I guess accessing List.Count is slower and the compiler doesn't optimize it to only run once.
Upvotes: 0
Reputation: 5914
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.
Upvotes: 18
Reputation: 19646
This entirely depends on what values
is. Count
could be implemented completely differently, depending on what the type of this object is.
If you are talking about a generic List<T>
- then Count is implemented as an internal property that isn't re-evaluated - and therefore is the better choice.
Upvotes: 3
Reputation: 27105
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'
Upvotes: 19