Performance of foreach vs classic for in C#

I found a list of the eight most common mistakes developers make in C#.

I share the opinion of the author regarding string concatenation and retrieving or saving data to BD in more than 1 call. A a lot of bad string concatenations eats your memory and N+1 anti-pattern when accessing BD breaks your app performance.

The post was useful for me as I learnt how rethrowing exception actually works. Very interesting. But I don’t buy the rest of the list, I think they can only be applied in very specific scenarios and they are not golden rules.

The entry number 7 of the list, the foreach vs for, called my attention. I had always suspected that for is faster than foreach but I had assumed that it was for a very little margin. I wanted to test if for myself, so I prepared a little solution and by the way I tested the performance of iterate an array vs generic list.

The result is this:
Graph

From left to right, the first column is the result from a for through a List, in which the constraint is the count property of the list cached on a variable:

var collection = new List();
[...]
var count = collection.Count;
for (int i = 0; i < count; i++)
{
  int aux = collection[i];
}

The second column is the same for loop, but this time the loop constraint is the property Count directly. The property will be evaluated in each iteration.

var collection = new List();
[...]
for (int i = 0; i < collection.Count; i++)
{
  int aux = collection[i];
}

The third column is a foreach through the List

var collection = new List();
[...]
foreach (var i in collection)
{
  int aux = i;
}

Next columns are the same loops as above but iterating through a primitive array. The times are expressed in milliseconds and my machine is an Intel i3 with 6GB RAM running Windows 8 x64. I am using Visual Studio 2012. The collection and the array have 10 million items to run the tests.

As I already said, I expected a little advantage for the for loop against the foeach, and there it is, a roughly 20%. But what I did not expected was that iterating through a generic list takes the double of the time than iterating trough an array, so bad.

There was another surprise, the gap from caching the limit of the for or not. I suppose that the count property from List is some kind of cache but evaluating the property in the loop hurts performance in about 40%. I can’t imagine why it occurs. That should be a getter of a private primitive integer field.

About these ads

One thought on “Performance of foreach vs classic for in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s