Skip to content

Instantly share code, notes, and snippets.

@VaclavElias
Last active July 5, 2023 08:49
Show Gist options
  • Save VaclavElias/b3b521205415d6ae1cf3d5ca9d9cad10 to your computer and use it in GitHub Desktop.
Save VaclavElias/b3b521205415d6ae1cf3d5ca9d9cad10 to your computer and use it in GitHub Desktop.
List - ConvertAll vs Select Benchmark
using BenchmarkDotNet.Attributes;
namespace Benchmark.Tests
{
[MemoryDiagnoser]
public class ConvertAllvsSelectBenchmark
{
[Params(10, 100)]
public int Iterations { get; set; }
public List<Apple> Items { get; set; } = new();
[GlobalSetup]
public void GlobalSetup()
{
Items.AddRange(Enumerable.Range(0, Iterations).Select(_ => new Apple()));
}
[Benchmark]
public void ConvertAllTest()
{
var items = Items.ConvertAll(s => s.Color);
}
[Benchmark]
public void SelectTest()
{
var items = Items.Select(s => s.Color).ToList();
}
}
public class Apple
{
public string Color { get; set; } = "Red";
public string Origin { get; set; } = "Not Specified";
public void ProcessCost() { }
}
}
@VaclavElias
Copy link
Author

VaclavElias commented Oct 7, 2021

Test on .NET 6

.NET SDK=6.0.100-rc.1.21463.6
[Host] : .NET 6.0.0 (6.0.21.45113), X64 RyuJIT
DefaultJob : .NET 6.0.0 (6.0.21.45113), X64 RyuJIT

Method Iterations Mean Error StdDev Gen 0 Allocated
ConvertAllTest 10 50.90 ns 1.028 ns 1.143 ns 0.0081 136 B
SelectTest 10 68.60 ns 1.401 ns 1.499 ns 0.0124 208 B
ConvertAllTest 100 361.99 ns 7.194 ns 8.564 ns 0.0510 856 B
SelectTest 100 425.84 ns 8.231 ns 7.699 ns 0.0553 928 B
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment