Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created June 20, 2024 20:35
Show Gist options
  • Save admir-live/ba8a629f63998c266304148a6cc59249 to your computer and use it in GitHub Desktop.
Save admir-live/ba8a629f63998c266304148a6cc59249 to your computer and use it in GitHub Desktop.
Avoid Using the "let" Keyword in LINQ Queries
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class LinqQueryPerformanceBenchmark
{
private List<Person> _peopleList;
public LinqQueryPerformanceBenchmark()
{
_peopleList = new List<Person>();
for (int index = 0; index < 10000; index++)
{
_peopleList.Add(new Person
{
FirstName = index % 2 == 0 ? "Admir" : "Tarik",
LastName = index % 3 == 0 ? "Haris" : "Velid"
});
}
}
[Benchmark]
public void FilterPeopleWithoutLet()
{
var filteredPeople = from person in _peopleList
where person.LastName.Contains("Haris")
&& person.FirstName.Equals("Admir")
select person;
}
[Benchmark]
public void FilterPeopleUsingLet()
{
var filteredPeople = from person in _peopleList
let isLastNameHaris = person.LastName.Contains("Haris")
let isFirstNameAdmir = person.FirstName.Equals("Admir")
where isLastNameHaris && isFirstNameAdmir
select person;
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
public class BenchmarkProgram
{
public static void Main(string[] args)
{
var benchmarkSummary = BenchmarkRunner.Run<LinqQueryPerformanceBenchmark>();
}
}
@admir-live
Copy link
Author

// * Summary *

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3737/23H2/2023Update/SunValley3)
AMD Ryzen 9 3900X, 1 CPU, 24 logical and 12 physical cores
.NET SDK 8.0.301
[Host] : .NET 8.0.6 (8.0.624.26715), X64 RyuJIT AVX2
DefaultJob : .NET 8.0.6 (8.0.624.26715), X64 RyuJIT AVX2

Method Mean Error StdDev
FilterPeopleWithoutLet 10.62 ns 0.182 ns 0.152 ns
FilterPeopleUsingLet 76.97 ns 1.577 ns 1.817 ns

@admir-live
Copy link
Author

Method Allocated
FilterPeopleWithoutLet 72 B
FilterPeopleUsingLet 360 B

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