Created
May 1, 2024 01:07
-
-
Save admir-live/0b4f8a1bdb52a6dae5439821ad9542ea to your computer and use it in GitHub Desktop.
This C# code defines benchmark tests to compare the performance of boxing (using a non-generic number class) versus non-boxing (using a generic number class) operations on numeric values.
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 System; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
public interface INumber | |
{ | |
object NumericValue { get; set; } | |
} | |
public class Number : INumber | |
{ | |
public object NumericValue { get; set; } | |
} | |
public interface INumber<T> | |
{ | |
T NumericValue { get; set; } | |
} | |
public class Number<T> : INumber<T> | |
{ | |
public T NumericValue { get; set; } | |
} | |
public class BoxingPerformanceBenchmark | |
{ | |
private readonly Number nonGenericNumber = new Number { NumericValue = 10 }; | |
private readonly Number<int> genericNumber = new Number<int> { NumericValue = 10 }; | |
[Benchmark] | |
public void BoxingBenchmark() | |
{ | |
var currentValue = nonGenericNumber.NumericValue; | |
nonGenericNumber.NumericValue = 20; | |
} | |
[Benchmark] | |
public void NonBoxingBenchmark() | |
{ | |
var currentValue = genericNumber.NumericValue; | |
genericNumber.NumericValue = 20; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var benchmarkSummary = BenchmarkRunner.Run<BoxingPerformanceBenchmark>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment