Skip to content

Instantly share code, notes, and snippets.

@aalmada
Last active July 5, 2023 12:12
Show Gist options
  • Save aalmada/027aa1a1124e7cea3d58da158f80b7a7 to your computer and use it in GitHub Desktop.
Save aalmada/027aa1a1124e7cea3d58da158f80b7a7 to your computer and use it in GitHub Desktop.
Benchmarking Enumerable.MaxBy() against Enumerable.OrderByDescending() followed by Enumerable.First()
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
namespace LinqBenchmarks;
public record Person(int Age);
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class MaxByBenchmarks
{
List<Person>? random;
List<Person>? bestCase;
List<Person>? worstCase;
[Params(100, 10_000)]
public int Count { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
var rnd = new Random(0);
random = Enumerable.Range(0, Count).Select(_ => new Person(rnd.Next())).ToList();
bestCase = Enumerable.Range(0, Count).Select(age => new Person(Count - age)).ToList();
worstCase = Enumerable.Range(0, Count).Select(age => new Person(age)).ToList();
}
[BenchmarkCategory("Random")]
[Benchmark(Baseline = true)]
public Person Random_OrderBy()
=> random!.OrderByDescending(person => person.Age).First();
[BenchmarkCategory("Random")]
[Benchmark]
public Person? Random_MaxBy()
=> random!.MaxBy(person => person.Age);
[BenchmarkCategory("Best Case")]
[Benchmark(Baseline = true)]
public Person BestCase_OrderBy()
=> bestCase!.OrderByDescending(person => person.Age).First();
[BenchmarkCategory("Best Case")]
[Benchmark]
public Person? BestCase_MaxBy()
=> bestCase!.MaxBy(person => person.Age);
[BenchmarkCategory("Worst Case")]
[Benchmark(Baseline = true)]
public Person WorstCase_OrderBy()
=> worstCase!.OrderByDescending(person => person.Age).First();
[BenchmarkCategory("Worst Case")]
[Benchmark]
public Person? WorstCase_MaxBy()
=> worstCase!.MaxBy(person => person.Age);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment