Skip to content

Instantly share code, notes, and snippets.

@kshyju
Created February 8, 2023 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kshyju/d5c528bb590a18c49c6c1fe6beb17243 to your computer and use it in GitHub Desktop.
Save kshyju/d5c528bb590a18c49c6c1fe6beb17243 to your computer and use it in GitHub Desktop.
LINQ Where+SingleOrDefault vs SingleOrDefault Benchmarks
using BenchmarkDotNet.Attributes;
namespace Benchmarks
{
public record Foo(string Name, string Value, int category);
[MemoryDiagnoser]
public class LinqBenchmarks
{
private IEnumerable<Foo> items;
[GlobalSetup]
public void Init()
{
items = new List<Foo>
{
new Foo("Phone", "Apple", 3),
new Foo("Computer", "Dell", 2),
new Foo("Pen", "F", 2)
};
}
[Benchmark]
public Foo? Where_SingleOrDefault()
{
return items.Where(s => string.Equals(s.Name, "Pen", StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
}
[Benchmark]
public Foo? SingleOrDefault()
{
return items.SingleOrDefault(s => string.Equals(s.Name, "Pen", StringComparison.OrdinalIgnoreCase));
}
}
}
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22621
11th Gen Intel Core i7-1185G7 3.00GHz, 1 CPU, 8 logical and 4 physical cores
.NET SDK=7.0.102
  [Host]     : .NET 6.0.13 (6.0.1322.58009), X64 RyuJIT
  DefaultJob : .NET 6.0.13 (6.0.1322.58009), X64 RyuJIT

Method Mean Error StdDev Gen 0 Allocated
Where_SingleOrDefault 54.48 ns 1.127 ns 1.384 ns 0.0114 72 B
SingleOrDefault 46.89 ns 0.803 ns 0.859 ns 0.0063 40 B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment