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?
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With