LINQ (Language INtegrated Query) is a set of features in C# for concise and declarative code. I use it pretty much wherever I can, but sometimes I wonder and people ask: is this a performance trap? It would be painful to have to replace many usages of LINQ with other constructs in addition to time spent finding that to be an actual bottleneck. Let’s do a basic benchmark to see what using LINQ might cost us compared to more traditional constructs such as for and foreach loops, and see if this worry is valid.

Methodology

I used the BenchmarkDotNet library. The experiment code can be found here. All benchmarks are of functions that operate on Customer arrays, where a Customer is an immutable struct with an int Age and a string Name. Note that these methods would normally be parameterized, taking the Customer array as an argument; however it is easier to use BenchmarkDotNet with methods that take no arguments.

I ran these benchmarks on my laptop, which is a 2020 Dell Inspiron 5591 2-in-1 with Intel Core i5–10210U, 16GB RAM (8GB original, 8GB DDR4–3200 from Crucial), running Windows 10 Home 1909. The code runs on .NET Core 3.1. BenchmarkDotNet runs each experiment — in this case a unique size and implementation — 100 times and measures statistics on those runs. All line charts comparing implementations are of the average run time across those runs.

Benchmark: Iteration

Each implementation returns the number of Customer’s in the array that have an age under 18 (that is, are minors). Baseline implementations using for/foreach:

Image for post

…and two using LINQ Count:

Image for post

Image for post

Image for post

Image for post

Image for post

The LINQ implementation using Select and then Count with no arguments has a similar slope plus a small overhead penalty compared to for/foreach (overlaid on the graph because they’re so close). However the LINQ implementation using Count that takes a predicate function on the elements has a significant performance penalty and the slope of the graph is much steeper. This was a surprising result to me.

#performance #functional-programming #linq #c-sharp-programming #programming-c #c-sharp

Is Using LINQ in C# Bad for Performance?
8.15 GEEK