Skip to content

Instantly share code, notes, and snippets.

@tsvayer
Created July 18, 2021 15:21
Show Gist options
  • Select an option

  • Save tsvayer/5a570a8eabfd4e671c6237b1661c19e0 to your computer and use it in GitHub Desktop.

Select an option

Save tsvayer/5a570a8eabfd4e671c6237b1661c19e0 to your computer and use it in GitHub Desktop.
Benchmark MaxBy
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
using NUnit.Framework;
namespace TestProject1
{
public record Employee(string Name, int HoursPerWeek);
[SimpleJob]
public class MaxByBenchmarks
{
static readonly Random Rnd = new();
List<Employee> employees;
[GlobalSetup]
public void Setup()
{
employees = Generate().ToList();
}
[Benchmark]
public void Aggregating() =>
employees
.Aggregate((max, next) => next.HoursPerWeek > max.HoursPerWeek
? next
: max);
[Benchmark]
public void Sorting() =>
employees.OrderByDescending(x => x.HoursPerWeek).First();
IEnumerable<Employee> Generate()
{
const int count = 100000;
for (var i = 0; i < count; i++)
yield return new Employee(
$"name{i}",
Rnd.Next(count));
}
}
public class BenchmarkTests
{
[Test]
public void BenchmarkMaxBy()
{
var manualConfig = DefaultConfig.Instance
.WithOptions(ConfigOptions.DisableOptimizationsValidator);
BenchmarkRunner.Run<MaxByBenchmarks>(manualConfig);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment