Skip to content

Instantly share code, notes, and snippets.

@stphnwlsh
Last active June 22, 2022 06:00
Benchmarking to the Bottom - Iterating Arrays in .NET
[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