Created
January 25, 2022 13:01
-
-
Save Zastai/1fbaa1e5f290ee46999361adbca6424d to your computer and use it in GitHub Desktop.
benchmark for type checks
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
#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