Which is faster to loop through with a foreach
?
To iterate over, a list will be orders of magnitude faster. Just take a gander at the Lookup.GetEnumerator()
function and how much work it's doing because it doesn't store the original elements in a list:
public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator() {
Grouping g = lastGrouping;
if (g != null) {
do {
g = g.next;
yield return g;
} while (g != lastGrouping);
}
}
I actually sat down and wrote a benchmark for it:
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.17763.1282 (1809/October2018Update/Redstone5)
Intel Core i7-8850H CPU 2.60GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=5.0.100-preview.4.20258.7
[Host] : .NET Core 3.1.4 (CoreCLR 4.700.20.20201, CoreFX 4.700.20.22101), X64 RyuJIT [AttachedDebugger]
DefaultJob : .NET Core 3.1.4 (CoreCLR 4.700.20.20201, CoreFX 4.700.20.22101), X64 RyuJIT
| Method | n | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|----------- |------- |---------------:|-------------:|-------------:|---------:|------:|------:|----------:|
| LookupTest | 100 | 2,733.6 ns | 25.08 ns | 22.23 ns | 0.8583 | - | - | 4048 B |
| ListTest | 100 | 263.6 ns | 1.54 ns | 1.20 ns | - | - | - | - |
| LookupTest | 1000 | 27,185.6 ns | 245.01 ns | 217.20 ns | 8.4839 | - | - | 40048 B |
| ListTest | 1000 | 2,306.6 ns | 22.53 ns | 19.97 ns | - | - | - | - |
| LookupTest | 10000 | 274,364.4 ns | 5,041.13 ns | 6,554.89 ns | 84.9609 | - | - | 400048 B |
| ListTest | 10000 | 22,903.7 ns | 178.62 ns | 158.34 ns | - | - | - | - |
| LookupTest | 100000 | 2,774,880.1 ns | 49,165.10 ns | 58,527.55 ns | 847.6563 | - | - | 4000008 B |
| ListTest | 100000 | 231,208.2 ns | 4,449.43 ns | 4,369.93 ns | - | - | - | - |