For versus Foreach in C#

As a C# Performance Architect, your job is to create solution architectures that provide the best possible performance for your business or organization. And to do your job well, you’ll need a solid understanding of basic C# code optimizations.

In this post, we’ll look at the different types of loops in C#. Understanding the difference will help you pick the correct code fragment for every occasion.

Take a look at the following code.

static void Main(string[] args)
{
    var list = GetSomeLargeList();
    foreach (int number in list) 
    {
        // do something with number
    }
}

It’s a simple foreach-loop that sequentially iterates through each element in a large list of integers.

But wait! There’s another way of doing this. Check out this code:

static void Main(string[] args)
{
    var list = GetSomeLargeList();
    for (int i=0; i < list.Count; i++) 
    {
        var number = list[i];
        // do something with number
    }
}

It’s basically the same code, but now I’m using a normal for-loop to iterate through the numbers.

Which code do you think is faster?

It’s pretty much the same code. Either I am using foreach, or I’m using for. But in both cases, I need to loop through each element in the list. So you would expect the same execution time, right?

Well, check it out. I’ve coded a quick benchmark to compare the two:

Did you see the results? The first benchmark with the foreach-loop took 273 milliseconds. The second benchmark with the for-loop took only 112 milliseconds. The for-loop is 2.4 times faster than the foreach-loop.

That’s a big difference. The reason becomes clear when we look at foreach in detail. What looks like a simple loop on the outside is actually a complex data structure called an enumerator:

An enumerator is a data structure with a  Current property, a MoveNext method, and a  Reset method. The Current property holds the value of the current element, and every call to MoveNext advances the enumerator to the next item in the sequence.

Enumerators are great because they can handle any iterative data structure. In fact, they are so powerful that all of LINQ is built on top of enumerators.

But the disadvantage of enumerators is that they require calls to  Current and  MoveNext for every element in the sequence. All those method calls add up, especially in mission-critical code.

Conversely, the for-loop only has to call get_Item for every element in the list. That’s one method call less than the foreach-loop, and the difference really shows.

So when should you use a foreach-loop, and when should you use a for-loop?

Here’s what you need to do:

  • When you’re using LINQ, use foreach
  • When you’re working with very large computed sequences of values, use foreach
  • When performance isn’t an issue, use foreach
  • But if you want top performance, use a for-loop instead

 

 

Would you like to know more? I’ve created a series of blog posts on C# performance optimization. Each post is based on content from my courses and from actual techniques I’ve used in the field.

Take a look:


Also published on Medium.