Deep Dive into .NET Performance: Span.Sort and LINQ Uncovered

PROSTO24’s editorial team continues its in-depth investigation into the performance characteristics of core .NET components. Recent benchmarks have unveiled unexpected nuances in the behavior of sorting mechanisms, specifically Span.Sort and LINQ OrderBy, which could significantly impact application efficiency.

Span.Sort: Struct Comparators and Memory Consumption

Conventional wisdom suggested that utilizing the Span.Sort overload with a struct comparator would yield superior performance compared to a class comparator, primarily due to optimized memory allocation. However, comprehensive benchmarks conducted on .NET 8, 9, and 10 revealed a counterintuitive outcome. These tests indicated that the struct comparator not only consumes more memory but also exhibits poorer time performance, surpassing the overhead of its class counterpart. While .NET 11 introduces changes, the improvements are not universally observed across all scenarios, necessitating further detailed analysis.

LINQ OrderBy: The Hidden Pitfalls of Full Sorts

Another area where performance can be deceptively complex is the application of the LINQ OrderBy method. Our research demonstrated that some calls following OrderBy execute a single pass over the collection, whereas others, despite appearing similar in code, trigger a complete and resource-intensive sort of the entire dataset. Distinguishing these scenarios visually from the code alone proves challenging. To expose these subtle performance traps, control measurements were conducted using a comparator invocation counter across four different machine configurations and four runtime versions, allowing for precise identification of instances where a full sort occurs versus an optimized pass.