Skip to content

Instantly share code, notes, and snippets.

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