In general I tend to use IEnumerable<>
as the type when I pass in parameters. However according to BenchmarkDotNet:
[Benchmark]
public void EnumeratingCollectionsBad()
{
var list = new List<string>();
for (int i = 0; i < 1000; i++)
{
Bad(list);
}
}
[Benchmark]
public void EnumeratingCollectionsFixed()
{
var list = new List<string>();
for (int i = 0; i < 1000; i++)
{
Fixed(list);
}
}
private static void Bad(IEnumerable<string> list)
{
foreach (var item in list)
{
}
}
private static void Fixed(List<string> list)
{
foreach (var item in list)
{
}
}
Method | Job | Runtime | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated |
---|---|---|---|---|---|---|---|---|---|---|
EnumeratingCollectionsBad | .NET Core 3.1 | .NET Core 3.1 | 17.802 us | 0.3670 us | 1.0764 us | 17.338 us | 6.3782 | - | - | 40032 B |
EnumeratingCollectionsFixed | .NET Core 3.1 | .NET Core 3.1 | 5.015 us | 0.1003 us | 0.2535 us | 4.860 us | - | - | - | 32 B |
Why would the interface version be so much slower (and memory intensive) than the concrete version?