Skip to content

Analyzer suggestion : replace .OrderBy().First() with MinBy() #87921

@nalka0

Description

@nalka0

The goal of the rule is to prevent sorting a whole collection where only a min/max is required.

Here are the results of a benchmark conducted on a List<double> ranging from -N to N-1 (all integers, cast to double only to match Shuffler.Shuffle's signature) shuffled by Perfolizer.Mathematics.Randomization.Shuffler

BenchmarkDotNet=v0.13.5, OS=Windows 10 (10.0.19045.2965/22H2/2022Update)
AMD Ryzen 5 4600H with Radeon Graphics, 1 CPU, 12 logical and 6 physical cores
.NET SDK=7.0.302
  [Host]     : .NET 7.0.5 (7.0.523.17405), X64 RyuJIT AVX2
  DefaultJob : .NET 7.0.5 (7.0.523.17405), X64 RyuJIT AVX2

Method N Mean Error StdDev
OrderByFirst 1000 24.81 μs 0.038 μs 0.034 μs
MinBy 1000 17.77 μs 0.108 μs 0.096 μs
OrderByDescendingLast 1000 23.87 μs 0.068 μs 0.060 μs
OrderByDescendingFirst 1000 25.37 μs 0.063 μs 0.059 μs
MaxBy 1000 17.71 μs 0.028 μs 0.023 μs
OrderByLast 1000 24.49 μs 0.093 μs 0.078 μs
OrderByFirst 10000 250.73 μs 3.916 μs 3.472 μs
MinBy 10000 189.40 μs 1.198 μs 1.000 μs
OrderByDescendingLast 10000 247.57 μs 0.478 μs 0.447 μs
OrderByDescendingFirst 10000 252.70 μs 0.899 μs 0.751 μs
MaxBy 10000 166.38 μs 0.046 μs 0.036 μs
OrderByLast 10000 243.11 μs 0.961 μs 0.852 μs

I have identified the following cases :

  • OrderBy(...).First() => MinBy(...)
  • OrderBy(...).Last() => MaxBy(...)
  • OrderByDescending(...).First() => MaxBy(...)
  • OrderByDescending(...).Last() => MinBy(...)

✅ You may also want to consider .ElementAt(0) the same as .First()

⚠️ Since there's (afaik) no easy conversion from OrderBy(...).ThenBy(...).First() to MinBy (and same for all the variants described above) the rule should probably only apply when there's no ThenBy

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions