/Benchmark_Methods_Lists.cs Secret
Last active
June 22, 2022 06:00
Benchmarking to the Bottom - Iterating Lists in .NET
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
[Benchmark] | |
public void For() | |
{ | |
for (var i = 0; i < this.N; i++) | |
{ | |
var allocated = $"{this.benchmarkList[i]}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void ForEach() | |
{ | |
foreach (var item in this.benchmarkList) | |
{ | |
var allocated = $"{item}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void ForEachLinq() | |
{ | |
this.benchmarkList.ForEach(item => | |
{ | |
var allocated = $"{item}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
}); | |
} | |
[Benchmark] | |
public void GetEnumerator() | |
{ | |
var enumerator = this.benchmarkList.GetEnumerator(); | |
while (enumerator.MoveNext()) | |
{ | |
var allocated = $"{enumerator.Current}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void SpanFor() | |
{ | |
var span = CollectionsMarshal.AsSpan(this.benchmarkList); | |
for (var i = 0; i < this.N; i++) | |
{ | |
var allocated = $"{span[i]}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void SpanForEach() | |
{ | |
var span = CollectionsMarshal.AsSpan(this.benchmarkList); | |
foreach (var item in span) | |
{ | |
var allocated = $"{item}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment