Skip to content

Instantly share code, notes, and snippets.

@yegorandrosov
Created December 15, 2020 17:48
Show Gist options
  • Save yegorandrosov/1f245cf24b8d1f20328e1b3790adb640 to your computer and use it in GitHub Desktop.
Save yegorandrosov/1f245cf24b8d1f20328e1b3790adb640 to your computer and use it in GitHub Desktop.
Benchmark related to conversation https://stackoverflow.com/a/65302363/7313094
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Generic;
namespace ConsoleApp4
{
public abstract class BaseType
{
public abstract string Type { get; set; }
}
public class ChildTypeA : BaseType
{
public override string Type { get; set; } = "ChildTypeA";
}
public class ChildTypeB : BaseType
{
public override string Type { get; set; } = "ChildTypeB";
}
public class ChildTypeC : BaseType
{
public override string Type { get; set; } = "ChildTypeC";
}
public class SwitchCaseStringVsPatternMatching
{
private const int n = 3_000_000;
private List<BaseType> data = new List<BaseType>(n);
public SwitchCaseStringVsPatternMatching()
{
var random = new Random();
for (var i = 0; i < n; i++)
{
var next = random.NextDouble();
if (next < 0.33)
{
data.Add(new ChildTypeA());
}
else if (next < 0.66)
{
data.Add(new ChildTypeB());
}
else
{
data.Add(new ChildTypeC());
}
}
}
[Benchmark]
public void UseGetTypeNameString()
{
foreach (var item in data)
{
var typeName = item.GetType().Name;
switch (typeName)
{
case "ChildTypeA":
break;
case "ChildTypeB":
break;
case "ChildTypeC":
break;
}
}
}
[Benchmark]
public void UseTypeString()
{
foreach (var item in data)
{
var typeName = item.Type;
switch (typeName)
{
case "ChildTypeA":
break;
case "ChildTypeB":
break;
case "ChildTypeC":
break;
}
}
}
[Benchmark]
public void UsePatternMatching()
{
foreach (var item in data)
{
switch (item)
{
case ChildTypeA a:
break;
case ChildTypeB b:
break;
case ChildTypeC c:
break;
}
}
}
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<SwitchCaseStringVsPatternMatching>();
}
}
}
@yegorandrosov
Copy link
Author

Method Mean Error StdDev
UseGetTypeNameString 132.64 ms 2.605 ms 5.437 ms
UseTypeString 90.44 ms 1.788 ms 1.914 ms
UsePatternMatching 40.62 ms 0.702 ms 0.862 ms

@yegorandrosov
Copy link
Author

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.685 (2004/?/20H1)
Intel Core i7-2920XM CPU 2.50GHz (Sandy Bridge), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=5.0.100
[Host] : .NET Core 3.1.10 (CoreCLR 4.700.20.51601, CoreFX 4.700.20.51901), X64 RyuJIT
DefaultJob : .NET Core 3.1.10 (CoreCLR 4.700.20.51601, CoreFX 4.700.20.51901), X64 RyuJIT

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