Poor performance of OfType<T> and Cast<T>
Description
The performance of the .OfType<T> and .Cast<T> methods are suboptimal in many cases. For example, while essentially equivalent:
people.Cast<Person>().ToList() runs about 4 times as slow and takes 4 times the memory as people.Select(x => (Person)x).ToList() while being essentially logically equivalent.
// * Summary *
BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22000.856/21H2) AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores .NET SDK=6.0.203 [Host] : .NET 6.0.8 (6.0.822.36306), X64 RyuJIT AVX2 DefaultJob : .NET 6.0.8 (6.0.822.36306), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Allocated |
|---|---|---|---|---|
| Cast | 177.81 us | 1.554 us | 1.378 us | 256.41 KB |
| Cast_Select | 43.62 us | 0.396 us | 0.331 us | 78.25 KB |
| OfType | 193.63 us | 2.182 us | 2.041 us | 256.41 KB |
| OfType_As | 97.13 us | 1.330 us | 1.244 us | 256.47 KB |
| OfExactlyType | 82.80 us | 0.805 us | 0.753 us | 256.47 KB |
Configuration
Tested on .Net Core 6.0.8, windows 11 x64.
Other information
CastIterator is on Enumerable, while the SelectListIterator/SelectArrayIterator/SelectEnumerableIterator is a generic iterator. Creating optimized versions of the Cast/OfType methods could lead to significant performance increases.
Credit for finding this should go to Nick Chapsas: https://youtu.be/dIu5EisoB_s