How slow is LINQ?

A real-life example of LINQ queries optimization.

Disclaimer

Write clean code. Measure. Optimize.
Optimization of LINQ is necessary only when it is the root of the problem.

Introduction

Project

I’m working on an open-source pet project called QueryNinja that provides dynamic query building. Changes defined in this article are related to version v1.1.0 and will be applied in future releases. The main execution path includes creating the query using Asp.Net Core ModelBinding and translating the query to Expression Trees.

LINQ vs. ‘for’ loop

‘For’ loops is robust and straightforward. No heap allocations are needed to execute the loop. Also, accessing the Array or List element by the index is a constant time operation.

LINQ version of the query
‘For’ loop example

The Problem

As an owner of the QueryNinja, I assume that Performance is one of the main features. I’m aimed at minimization the impact that my package makes on the application performance.

Create IQueryComponent for all suitable query string parameters
  • IQueryComponentFactory knows how to create IQueryComponent from query string parameter.
  • This method is also an Iterator.

Optimization

As a starting point, I’ve already created several benchmarks with BenchmarkDotNet. They cover several parts of my package's main execution path but let’s focus on the ModelBinderBenchmarks.

ModelBinder benchmark
  • Benchmark has multiple scenarios, but we will use only one of them that focuses on the GetQueryComponents method.
Benchmarks with Baseline
GetQueryComponents with ‘For’ loop
  • 10 OrderingRule Query Parameters
  • 10 Select Query Parameters
  • 30 mixed Query Parameters
  • No Query Parameters
ModelBinder Benchmark with all senarios
  • Fewer GC invocations take place as well.
  • Empty Query takes a bit more time to execute for some reason.

Conclusion

Simple LINQ queries can have performance similar to ‘For’ lops. However, they require much more allocations to operate.

References

I’m not affiliated with any of the tools except QueryNinja. All recommendations here are tools that I’m using in my work.

Source Code

Articles

Tools Used

Lead Software Engineer at EPAM

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store