Skip to content

Instantly share code, notes, and snippets.

@Zastai
Created January 25, 2022 13:01
Show Gist options
  • Save Zastai/1fbaa1e5f290ee46999361adbca6424d to your computer and use it in GitHub Desktop.
Save Zastai/1fbaa1e5f290ee46999361adbca6424d to your computer and use it in GitHub Desktop.
benchmark for type checks
#LINQPad optimize+
class Info {
public char Type;
}
class Base {
public Base() : this('B') {
}
protected Base(char type) {
this.Info = new Info { Type = type };
}
public Info Info { get; private set; }
}
class Derived : Base {
public Derived() : base('D') { }
}
public class TypeCheckBenchmarks {
private readonly Base Object1 = new Base();
private readonly Base Object2 = new Derived();
int counter = 0;
[Benchmark]
public void TestUsingIsOperatorWhenFalse()
{
if (this.Object1 is Derived)
{
++counter;
}
else
{
--counter;
}
if (this.Object2 is Base)
{
++counter;
}
else
{
--counter;
}
}
[Benchmark]
public void TestUsingIsOperatorWhenTrue()
{
if (this.Object1 is Base)
{
++counter;
}
else
{
--counter;
}
if (this.Object2 is Derived)
{
++counter;
}
else
{
--counter;
}
}
[Benchmark]
public void TestUsingPropertyWhenFalse()
{
if (this.Object1.Info.Type == 'D')
{
++counter;
}
else
{
--counter;
}
if (this.Object2.Info.Type == 'B')
{
++counter;
}
else
{
--counter;
}
}
[Benchmark]
public void TestUsingPropertyWhenTrue()
{
if (this.Object1.Info.Type == 'B')
{
++counter;
}
else {
--counter;
}
if (this.Object2.Info.Type == 'D')
{
++counter;
}
else
{
--counter;
}
}
[Benchmark]
public void TestUsingTypeOfWhenFalse()
{
if (this.Object1.GetType() == typeof(Derived))
{
++counter;
}
else
{
--counter;
}
if (this.Object2.GetType() == typeof(Base))
{
++counter;
}
else
{
--counter;
}
}
[Benchmark]
public void TestUsingTypeOfWhenTrue()
{
if (this.Object1.GetType() == typeof(Base))
{
++counter;
}
else
{
--counter;
}
if (this.Object2.GetType() == typeof(Derived))
{
++counter;
}
else
{
--counter;
}
}
}
public static void Main() {
BenchmarkRunner.Run<TypeCheckBenchmarks>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment