Created
June 20, 2024 20:35
-
-
Save admir-live/ba8a629f63998c266304148a6cc59249 to your computer and use it in GitHub Desktop.
Avoid Using the "let" Keyword in LINQ Queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | |
} | |
} |
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
// * 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