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

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