Performance of foreach loops vs. LINQ

Written on

After discovering LINQ, it's tempting to use it all the time, even in place of a basic foreach loop, but I've only recently looked into the performance of LINQ compared with the "old" C# coding techniques we're all used to.

From what I have tested myself and read elsewhere, it seems that LINQ is slightly slower than for example foreach loops when doing basic operations. Let's say we have the the following class:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public double Salary { get; set; }
}

Now let's assume we want to get all Employees that have a salary greater than 50000.00. To do this using a traditional foreach loop we would do something similar to this:

List employees = GetEmployees();
List highEarners = new List();

foreach (Employee employee in employees)
{
    if (employee.Salary > 50000.00)
    {
        highEarners.Add(employee);
    }
}

return highEarners;

The LINQ equivalent would be this:

List employees = GetEmployees();

var highEarners = from employee in employees
                  where employee.Salary > 50000.00
                  select employee;

highEarners.ToList();

I tested the foreach loop and its LINQ equivalent against a collection of a million items and found that the LINQ version was anywhere between 1.5 to 3 times slower. Another article testing the same thing (LINQ vs Loop - A performance test) pointed out (in the comments) that you can seriously slow down your LINQ query (make it upto 10 times slower) by accidentally writing your LINQ statement the wrong way. Write LINQ with care.

If you've replaced a simple foreach with some LINQ, you've slowed things down but you're probably not going to get a noticable performance hit unless you're dealing with many millions of items - but it's definately not beneficial to use LINQ in this scenario.

In an interview recently I mentioned this performance hit, and the interviewer asked me "well then when should you use LINQ?" and I'm going to answer that in my next couple of posts, because it's a question I've been wondering about a lot recently.


Comments