I am stepping through a large list of object to do some stuff regarding said objects in the list.
During my iteration, I will remove some objects from the list depen
You can use a decompiler, such as the freely-available ILSpy, to answer these questions. If you're referring to the List<T>
type, then the Count
getter simply involves reading a field:
public int Count
{
get { return this._size; }
}
List
is implemented as an array list, and it keeps track of its own size, so invoking the .Count
property doesn't require any iteration.
If you call the LINQ .Count()
extension method, this will check whether the underlying IEnumerable<>
implements ICollection
(which a List<>
does), and use the .Count
property on that interface if possible. So this won't cause any iteration to occur either.
Incidentally, there are other problems you're going to encounter if you attempt to remove items from your list while iterating through it. It's not really clear how iteration should behave when you are removing elements out from under the iterator, so List<>
s will avoid this issue entirely by throwing an exception if the list has been modified since its enumerator was created.
It simply keeps an internal int to track the number of items. So no iteration. The documentation says retrieving Count is an O(1) operation:
http://msdn.microsoft.com/en-us/library/27b47ht3%28v=vs.110%29.aspx
You can see for yourself:
http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
As stated here under the remarks tab http://msdn.microsoft.com/en-us/library/27b47ht3(v=vs.110).aspx
Retrieving the value of this property is an O(1) operation.
Which means no iteration is occurring.
You tagged your question with both vb.net and c#, so in reply to "If .net physically re-iterates through the list, I may just as well keep a counter on my own iteration through the list, and save the overhead?"
If your iteration is with a For i = first To last
then VB.NET will evaluate first
and last
when it enters the loop:
Dim first As Integer = 1
Dim last As Integer = 3
For i = first To last
Console.Write(i.ToString() & " ")
last = -99
Next
outputs: 1 2 3
If you do the equivalent in C#, first
and last
are evaluated on every iteration:
int first = 1;
int last = 1;
for (int i = first; i <= last; i++)
{
Console.Write(i.ToString() + " ");
last = -99;
}
outputs: 1
If your .Count() function/property is expensive to evaluate and/or you don't want it to be re-evaluated on each iteration (for some other reason), then in C# you could assign it to a temporary variable.