Skip to content

Instantly share code, notes, and snippets.

@sonnemaf
Created October 30, 2024 09:33
Show Gist options
  • Save sonnemaf/bc0f201bfa6fabad4847359822986af4 to your computer and use it in GitHub Desktop.
Save sonnemaf/bc0f201bfa6fabad4847359822986af4 to your computer and use it in GitHub Desktop.
Benchmark LINQ First(…) vs Where(…).First() vs Find() in using .NET9, .NET8 and .NET4.8
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<BM>();
[HideColumns("Job", "StdDev", "RatioSD", "Alloc Ratio")]
[MemoryDiagnoser(displayGenColumns: false)]
[SimpleJob(RuntimeMoniker.Net90)]
[SimpleJob(RuntimeMoniker.Net80)]
[SimpleJob(RuntimeMoniker.Net48)]
public class BM {
private readonly List<Employee> _employees =
Enumerable.Range(0, 1024).Select(i => new Employee("Fons", i)).ToList();
[Benchmark(Baseline = true)]
public Employee? ListFind() =>
_employees.Find(emp => emp.Salary > 500);
[Benchmark]
public Employee? LinqFirstOrDefault() =>
_employees.FirstOrDefault(emp => emp.Salary > 500);
[Benchmark]
public Employee? LinqWhereFirstOrDefault()
=> _employees.Where(emp => emp.Salary > 500).FirstOrDefault();
}
public record class Employee(string Name, decimal Salary);
@sonnemaf
Copy link
Author

Don't forget to update your project file. You need Polysharp to use the record class in NET4.8

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFrameworks>net9.0;net8.0;net4.8</TargetFrameworks>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <LangVersion>latest</LangVersion> 
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="BenchmarkDotNet" Version="*" />
        <PackageReference Include="PolySharp" Version="1.14.1">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference> 
    </ItemGroup>

</Project>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment