Collection Performance: Exercise Caution When Using Take() with a Basic Count

The LINQ method Take() is frequently employed to extract a portion of a collection and assign it to a variable, as demonstrated in this example:

var result = people.Take(100);

Some code analyzers might suggest using a range, as illustrated here:

var result = people.Take(0..(Index)100);

However, it’s essential to consider whether using a range is more performant for a straightforward count like this.

Benchmark Results

The benchmark results reveal that using Take() with a simple count is 1.59 times faster than employing a range. Both methods allocate 80 bytes in memory.

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

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 reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply