Skip to content

Instantly share code, notes, and snippets.

@joncloud
Last active May 12, 2020 19:24
Show Gist options
  • Save joncloud/7f26af3f926ed9b365633be1a6b4b287 to your computer and use it in GitHub Desktop.
Save joncloud/7f26af3f926ed9b365633be1a6b4b287 to your computer and use it in GitHub Desktop.
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.778 (1909/November2018Update/19H2)
Intel Core i7-8850H CPU 2.60GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
  [Host]     : .NET Framework 4.8 (4.8.4150.0), X64 RyuJIT
  DefaultJob : .NET Framework 4.8 (4.8.4150.0), X64 RyuJIT

Method Mean Error StdDev Median Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
Linq_GetType 38.157 ns 0.7820 ns 2.1540 ns 37.740 ns 1.00 0.00 0.0068 - - 32 B
Linq_IsOperator 38.333 ns 0.7773 ns 1.1394 ns 38.099 ns 1.01 0.06 0.0068 - - 32 B
Linq_OfTypeAny 139.816 ns 2.7576 ns 4.2933 ns 140.143 ns 3.70 0.24 0.0186 - - 88 B
ForEach_GetType 3.600 ns 0.0484 ns 0.0404 ns 3.583 ns 0.10 0.01 - - - -
ForEach_IsOperator 3.561 ns 0.1012 ns 0.1165 ns 3.568 ns 0.09 0.01 - - - -
For_GetType 3.608 ns 0.0665 ns 0.0590 ns 3.632 ns 0.10 0.01 - - - -
For_IsOperator 4.241 ns 0.1123 ns 0.2918 ns 4.130 ns 0.11 0.01 - - - -
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net48</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.12.1" />
</ItemGroup>
</Project>
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Linq;
namespace ConsoleApp91
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<Tests>();
}
}
[MemoryDiagnoser]
public class Tests
{
static readonly object[] _values = new object[]
{
123,
DateTime.UtcNow,
"abc"
};
[Benchmark]
public bool Linq_GetType()
{
return _values.Any(x => x.GetType() == typeof(string));
}
[Benchmark]
public bool Linq_IsOperator()
{
return _values.Any(x => x is string);
}
[Benchmark]
public bool Linq_OfTypeAny()
{
return _values.OfType<string>().Any();
}
[Benchmark]
public bool ForEach_GetType()
{
return Test(_values);
static bool Test(object[] values)
{
foreach (var value in _values)
{
if (value.GetType() == typeof(string))
{
return true;
}
}
return false;
}
}
[Benchmark]
public bool ForEach_IsOperator()
{
return Test(_values);
static bool Test(object[] values)
{
foreach (var value in _values)
{
if (value is string)
{
return true;
}
}
return false;
}
}
[Benchmark]
public bool For_GetType()
{
var length = _values.Length;
for (var i = 0; i < length; i++)
{
var value = _values[i];
if (value.GetType() == typeof(string))
{
return true;
}
}
return false;
}
[Benchmark]
public bool For_IsOperator()
{
var length = _values.Length;
for (var i = 0; i < length; i++)
{
var value = _values[i];
if (value is string)
{
return true;
}
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment