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:
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.