Skip to content

Instantly share code, notes, and snippets.

@adamchester
Created June 18, 2016 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamchester/57fa05c082b00354595532c0e6b1c79e to your computer and use it in GitHub Desktop.
Save adamchester/57fa05c082b00354595532c0e6b1c79e to your computer and use it in GitHub Desktop.
Benchmark: Linq OfType<T>.ToArray() vs ForListToArray
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
namespace BenchmarkDotNet.Samples.Framework
{
public class Framework_LinqOfType_vs_ForListToArray
{
public class Base { }
public class Derived1 : Base { }
public class Derived2 : Base { }
public class Derived3 : Base { }
static readonly Base[] EvenDistribution = new Base[] { new Derived1(), new Derived2(), new Derived3() };
static readonly Base[] MostlyDerived1 = new Base[]
{
new Derived1(), new Derived1(), new Derived1(), new Derived1(), new Derived1(),
new Derived2(), new Derived2(), new Derived2(),
};
static readonly Base[] MostlyDerived2And3 = new Base[]
{
new Derived1(),
new Derived2(), new Derived2(), new Derived2(),
new Derived3(), new Derived3(), new Derived3(),
};
[Benchmark(Baseline = true)]
public Derived1[] LinqOfType()
{
return EvenDistribution.OfType<Derived1>().ToArray();
}
[Benchmark]
public Derived1[] ObjectArray()
{
// ReSharper disable once CoVariantArrayConversion
return GetElementsOfTypeToArray<Derived1>(EvenDistribution);
}
/// <summary>
/// Similar to <see cref="Enumerable.OfType{TResult}"/>, but faster.
/// </summary>
private static TResult[] GetElementsOfTypeToArray<TResult>(object[] tokens)
where TResult : class
{
var result = new List<TResult>(tokens.Length / 2);
for (var i = 0; i < tokens.Length; i++)
{
var token = tokens[i] as TResult;
if (token != null)
{
result.Add(token);
}
}
return result.ToArray();
}
}
}
@adamchester
Copy link
Author

Results

BenchmarkDotNet-Dev=v0.9.7.0+
OS=Windows
Processor=?, ProcessorCount=8
Frequency=2728062 ticks, Resolution=366.5606 ns, Timer=TSC
HostCLR=CORE, Arch=64-bit RELEASE [RyuJIT]
JitModules=?
1.0.0-preview1-002702

Type=Framework_LinqOfType_vs_ForListToArray  Mode=Throughput  Toolchain=Core  
Method Median StdDev Scaled
LinqOfType 267.3867 ns 16.6434 ns 1.00
ObjectArray 94.4059 ns 2.3747 ns 0.35

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