Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created May 1, 2024 01:07
Show Gist options
  • Save admir-live/0b4f8a1bdb52a6dae5439821ad9542ea to your computer and use it in GitHub Desktop.
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.
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