/Benchmark_Methods_Arrays.cs Secret
Last active
June 22, 2022 06:00
Benchmarking to the Bottom - Iterating Arrays 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 ForLoop() | |
{ | |
for (var i = 0; i < this.N; i++) | |
{ | |
var allocated = $"{this.benchmarkArray[i]}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void ForEachLoop() | |
{ | |
foreach (var item in this.benchmarkArray) | |
{ | |
var allocated = $"{item}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void ArrayForEach() | |
{ | |
Array.ForEach(this.benchmarkArray, item => | |
{ | |
var allocated = $"{item}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
}); | |
} | |
[Benchmark] | |
public void GetEnumerator() | |
{ | |
var enumerator = this.benchmarkArray.GetEnumerator(); | |
while (enumerator.MoveNext()) | |
{ | |
var allocated = $"{enumerator.Current}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void SpanFor() | |
{ | |
var span = this.benchmarkArray.AsSpan(); | |
for (var i = 0; i < this.N; i++) | |
{ | |
var allocated = $"{span[i]}"; | |
if (allocated == "NotEquals") | |
{ | |
Console.WriteLine(allocated); | |
}; | |
} | |
} | |
[Benchmark] | |
public void SpanForEach() | |
{ | |
var span = this.benchmarkArray.AsSpan(); | |
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