Collection Performance: Finding First or Last and Count

When you need to find the first or last item in a collection or obtain its count, many developers use the LINQ methods First(), Last(), or Count() as shown in this example:

var person = personCollection.First();
var person = personCollection.Last();
var count = personCollection.Count();

Another alternative for obtaining the same information without LINQ could be achieved like this:

var person = personCollection[0];
var person = personCollection[personCollection.Count - 1];
var count = personCollection.Count

Using LINQ is more readable, but is it more performant?

Benchmark Results

The straightforward answer is that using LINQ is generally three times less performant. If your code heavily depends on LINQ methods, I recommend refactoring it.

When I setup my EditorConfig to check for these issues, it looks like this: dotnet_diagnostic.CA1826.severity = error

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.