alexeyfv

Published on

- 1 min read

Use indexer instead of LINQ method

C# Performance Code Quality
img of Use indexer instead of LINQ method

This is part of a series where I analyze .NET code quality rules from a performance perspective. Today, let’s talk about CA1826: Use property instead of Linq Enumerable method.

Rule description

This rule simply asks not to use First(), Last(), Count() methods from LINQ with IReadOnlyList<T>:

   IReadOnlyList<string> list = ["str1", "str2", "str3"];
var first = list.First();   // CA1826
var last = list.Last();     // CA1826
var count = list.Count();   // CA1826

Instead, you should use indexer or Count property for better performance:

   IReadOnlyList<string> list = ["str1", "str2", "str3"];
var first = list[0];
var last = list[^1];
var count = list.Count;

Performance analysis

I wrote a simple benchmark to see how much LINQ methods really affect performance. The results are in the repo and on the diagram below.

Performance comparison chart between LINQ methods and indexer and Count property

Performance comparison between LINQ methods and indexer and Count property

As you can see, there’s a difference between LINQ and direct access. But the difference is very small — just a few microseconds on my machine.

Should you care?

In most cases, no. The performance gain is small. But if you’re writing high-performance code, or these LINQ methods appear in a loop, it might be worth to refactor your code.