With BencharkDot net, this benchmark creates a list of 10,000 strings then tests either OfType<T>
or Cast<T>
Here's the benchmark code:
/// <summary>
/// Want to check what is faster OfType or Cast when a enurable all has the same items
/// </summary>
[Config(typeof(Config))]
public class LinqCastBenchmarks
{
private class Config : ManualConfig
{
public Config()
{
Add(new MemoryDiagnoser());
}
}
public LinqCastBenchmarks()
{
_array = new List<object>();
_array.AddRange(Enumerable.Range(0, 10000).Select(x => x.ToString()));
}
private readonly List<object> _array;
[Benchmark(Baseline = true)]
public void OfType()
{
foreach (var i in _array.OfType<string>())
{
var a = i;
}
}
[Benchmark()]
public void Cast()
{
foreach (var i in _array.Cast<string>())
{
var a = i;
}
}
[Benchmark()]
public void ExplicitCast()
{
foreach (var i in _array)
{
var a = (string)i;
}
}
Host Process Environment Information:
BenchmarkDotNet.Core=v0.9.9.0
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4710HQ CPU 2.50GHz, ProcessorCount=8
Frequency=2435769 ticks, Resolution=410.5480 ns, Timer=TSC
CLR=MS.NET 4.0.30319.42000, Arch=32-bit RELEASE
GC=Concurrent Workstation
JitModules=clrjit-v4.6.1586.0
Type=LinqCastBenchmarks Mode=Throughput
Method | Median | StdDev | Scaled | Scaled-SD | Gen 0 | Gen 1 | Gen 2 | Bytes Allocated/Op |
------------- |------------ |---------- |------- |---------- |------ |------ |------ |------------------- | OfType | 254.8104 us | 4.9054 us | 1.00 | 0.00 | - | - | - | 41.13 | Cast | 210.4970 us | 7.5344 us | 0.84 | 0.03 | - | - | - | 43.58 | ExplicitCast | 44.1904 us | 1.2827 us | 0.17 | 0.01 | - | - | - | 2.47 |