Introduction
There are plenty of ways to improve the performance of the C# code. Here, in this article, we will see how to use three top methods to improve the performance using some tweaks and see the result of the change.
- Materializing LINQ Queries Once
- Loop Parallelization
- Use Struct Instead of Class wherever possible
Materializing LINQ Queries Once
(Don’t use Expression tree to hold the result but extract the result by executing it, whenever possible)
When writing LINQ queries using IEnumerable or IQueryable interfaces, developers can materialize (call ToList, ToArray or similar methods) or not to materialize queries immediately (Lazy loading).
The lack of materialization allows developers to work with collections lazily. But sometimes it becomes necessary to iterate over the same collection several times. If the query was not materialized by calling ToList/ToArray method, iterating over the collection multiple times will affect the performance of the application.
Here is a sample where we are testing the performance of a lazy loading LINQ query vs materialized query.
[MemoryDiagnoser]
public class LinqTest {
[Benchmark]
public void NoMaterializedTest() {
var list = Enumerable.Range(0, 50000000);
var filteredlist = list.Where(element => element % 100000 == 0);
foreach(var element in filteredlist) {
//some logic here
}
foreach(var element in filteredlist) {
// some logic here
}
foreach(var element in filteredlist) {
// some logic here
}
}
[Benchmark]
public void MaterializedTest() {
var list = Enumerable.Range(0, 5000000);
var filteredlist = list.Where(element => element % 10000 == 0).ToList();
//ToList() method will execute the expression tree and get the result for future purpose.
foreach(var element in filteredlist) {
// some logic here
}
foreach(var element in filteredlist) {
// some logic here
}
foreach(var element in filteredlist) {
// some logic here
}
}
public static void Main() {
//Execute LinqTest class methods to check the benchmark
var result = BenchmarkRunner.Run < LinqTest > ();
}

Here you can see the difference, Materialized queries perform three times better compared to lazy load LINQ queries. Although this approach will not work always as we might not execute the same result set multiple times. Always check the case before materializing the LINQ query.
Loop Parallelization
Foreach is the most commonly used loop nowadays after For loop. It gives flexibility to not worry about the loop count and it will run to the length of the collection.


Join the conversation! Your thoughts help the community grow.