C# Optimization – Performance degradation when using LINQ with a foreach

For this C# optimization test, I compared two different ways to work with a subset of objects in a list.

  1. Use in “if”, within the foreach statement
  2. Use a “.Where(x => {condition})” LINQ filter


Test Description

For this test, I created a list of 1,000,000 employee objects.

Each employee has a name and salary. To make it simple, the names and salaries were the numbers 1 to 1,000,000.

The program then went through the list, finding every employee object with a salary less than, or equal to, 500,000 and doubled their salary. So, 500,000 employees should be skipped over, and 500,000 should have their salary changed.

The app ran the test ten times, and averaged the results.

Loop code for the “if” method:

Loop code for the LINQ method


Test Results

Running in Release mode, there were some variations in the results. However, the LINQ method was always slower.

A typical run had results similar to these:

“if” method duration: 20.81576 milliseconds

LINQ method: 27.5471 milliseconds

Performance difference: LINQ method was 32.34% slower


Test Source Code

If you’re interested in repeating this test, the source code is available here: https://gist.github.com/ScottLilly/aff8be9033b309fcdff9.

The Test.cs code is the code behind a Windows form, with the btnStart_Click method used to run the test.

Leave a Reply

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