Tech Quiz: Some micro optimization

Optimize the following code:

doubletotalCount = 0;

for (int index = 0; index < numberOfRuns; index++)
    string[] values = GetData(index);
    totalCount += values.Count();


A simple optimization is to replace Count() with Length.
Count() is an extension method that looks something like this:
public static int Count<TSource>(this IEnumerable<TSource> source)
if (source == null)
throw Error.ArgumentNull(“source”);
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
return is2.Count;
ICollection is3 = source as ICollection;
if (is3 != null)
return is3.Count;
int num = 0;
    using (
IEnumerator<TSource> enumerator = source.GetEnumerator())
return num;
If an IEnumerable<TSource> can be cast to a ICollection or ICollection<TSource>, the extension method will use the Count property. If that’s not possible, it will enumerate all the elements and count the total.
The string array can be cast to a ICollection so it can use the shortcut by using the Count property. However, the Lenght property of the array accesses this directly and avoids the cast.
What’s more important to realize is, that if your collection does not implement ICollection, Count() will have to enumerate all the elements to count the total which can be a huge performance hit.

Wouter de Kort works as a lead architect and consultant. He helps organizations stay on the cutting edge of software development. Wouter focuses on DevOps. He loves solving complex problems and helping other developers to grow. Wouter authored the book DevOps on the Microsoft stack and a couple of other books. Wouter is a Microsoft MVP and an ALM Ranger. You can find him on Twitter (@wouterdekort), on his blog at and at the various conferences where Wouter speaks.


Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.