Created
June 18, 2016 05:40
-
-
Save adamchester/57fa05c082b00354595532c0e6b1c79e to your computer and use it in GitHub Desktop.
Benchmark: Linq OfType<T>.ToArray() vs ForListToArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results