Files

48 lines
956 B
C#
Raw Permalink Normal View History

using System.Collections.Generic;
2017-05-12 14:49:44 +02:00
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace Umbraco.Tests.Benchmarks;
/// <summary>
/// Want to check what is faster OfType or Cast when a enurable all has the same items
/// </summary>
[MemoryDiagnoser]
public class LinqCastBenchmarks
2017-05-12 14:49:44 +02:00
{
private readonly List<object> _array;
2017-05-12 14:49:44 +02:00
public LinqCastBenchmarks()
{
_array = new List<object>();
_array.AddRange(Enumerable.Range(0, 10000).Select(x => x.ToString()));
}
2017-05-12 14:49:44 +02:00
[Benchmark(Baseline = true)]
public void OfType()
{
foreach (var i in _array.OfType<string>())
2017-05-12 14:49:44 +02:00
{
var a = i;
2017-05-12 14:49:44 +02:00
}
}
2017-05-12 14:49:44 +02:00
[Benchmark]
public void Cast()
{
foreach (var i in _array.Cast<string>())
2017-05-12 14:49:44 +02:00
{
var a = i;
2017-05-12 14:49:44 +02:00
}
}
2017-05-12 14:49:44 +02:00
[Benchmark]
public void ExplicitCast()
{
foreach (var i in _array)
2017-05-12 14:49:44 +02:00
{
var a = (string)i;
2017-05-12 14:49:44 +02:00
}
}
2017-07-20 11:21:28 +02:00
}