Created
May 20, 2024 13:05
-
-
Save admir-live/e55961d07f83024fa531c26372e44aba to your computer and use it in GitHub Desktop.
Understanding Class Performance in C#
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
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace ClassBenchmark | |
{ | |
public class StandardClass | |
{ | |
public int StandardProperty { get; set; } | |
public int GetStandardProperty() => StandardProperty; | |
} | |
public sealed class SealedClass | |
{ | |
public int SealedProperty { get; set; } | |
public int GetSealedProperty() => SealedProperty; | |
} | |
public abstract class AbstractBaseClass | |
{ | |
public virtual int GetBaseProperty() => 0; | |
} | |
public class DerivedClass : AbstractBaseClass | |
{ | |
public int DerivedProperty { get; set; } | |
public override int GetBaseProperty() => DerivedProperty; | |
} | |
public class ExtendedStandardClass : StandardClass | |
{ | |
public int AdditionalProperty { get; set; } | |
public int GetAdditionalProperty() => AdditionalProperty; | |
} | |
public class ClassBenchmark | |
{ | |
private readonly StandardClass standardClassInstance = new StandardClass { StandardProperty = 42 }; | |
private readonly SealedClass sealedClassInstance = new SealedClass { SealedProperty = 42 }; | |
private readonly DerivedClass derivedClassInstance = new DerivedClass { DerivedProperty = 42 }; | |
private readonly ExtendedStandardClass extendedClassInstance = new ExtendedStandardClass { StandardProperty = 42, AdditionalProperty = 84 }; | |
[Benchmark(Baseline = true)] | |
public int BenchmarkStandardClassProperty() => standardClassInstance.GetStandardProperty(); | |
[Benchmark] | |
public int BenchmarkSealedClassProperty() => sealedClassInstance.GetSealedProperty(); | |
[Benchmark] | |
public int BenchmarkDerivedClassProperty() => derivedClassInstance.GetBaseProperty(); | |
[Benchmark] | |
public int BenchmarkExtendedClassStandardProperty() => extendedClassInstance.GetStandardProperty(); | |
[Benchmark] | |
public int BenchmarkExtendedClassAdditionalProperty() => extendedClassInstance.GetAdditionalProperty(); | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var benchmarkSummary = BenchmarkRunner.Run<ClassBenchmark>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Benchmark Results
Benchmark Results
Explanation of Results
Standard Class (StandardClass)
Sealed Class (SealedClass)
Derived Class (DerivedClass)
Extended Standard Class (ExtendedStandardClass)
Usage Guidelines
StandardClass
SealedClass
DerivedClass
ExtendedStandardClass
Factors Affecting Performance