Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does list.count physically iterate through the list to count it, or does it keep a pointer

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 depending on certain criteria.

Once all is done, I need to update the UI regarding the number of objects in my list. (List of T).

QUESTION:

When I call list.count, does .net actually iterate through the list to count it, or does it store the count as a property/variable?

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?

Thanks

like image 342
Louis van Tonder Avatar asked Jul 01 '14 18:07

Louis van Tonder


People also ask

What can be used to iterate over a list?

We often want to perform the same operation on every element in a list, like displaying each element or manipulating them mathematically. To do that, we can use a loop to iterate over each element, repeating the same code for each element.

Can a for loop be used to iterate over a list?

A for loop iterates through items the same way as while and do-while loops, but it can also iterate through a list or set.


1 Answers

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

like image 60
Dennis_E Avatar answered Sep 18 '22 21:09

Dennis_E