Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created April 21, 2018 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/0fd6fa47d05a21ad7fb559a615cd0460 to your computer and use it in GitHub Desktop.
Save ufcpp/0fd6fa47d05a21ad7fb559a615cd0460 to your computer and use it in GitHub Desktop.
ボックス化によるパフォーマンスへの影響
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Runtime.CompilerServices;
[MemoryDiagnoser]
public class BoxingPerformance
{
// 値型だけを受け付けたいとき、ValueType で引数を受け取るとボックス化が起きる
[MethodImpl(MethodImplOptions.NoInlining)]
static void A(ValueType value) { }
// ボックス化を避けたければこう書く
// where T : struct 制約付きのジェネリック メソッドを用意
[MethodImpl(MethodImplOptions.NoInlining)]
static void B<T>(T value) where T : struct { }
// ボックス化が起きる場合のベンチマーク
[Benchmark]
public void InvokeValueType()
{
for (int i = 0; i < 10000; i++)
{
A(1);
A(TimeSpan.FromSeconds(1));
A(PlatformID.Unix);
}
}
// ボックス化が起きない場合のベンチマーク
[Benchmark]
public void InvokeGeneric()
{
for (int i = 0; i < 10000; i++)
{
B(1);
B(TimeSpan.FromSeconds(1));
B(PlatformID.Unix);
}
}
}
class Program
{
static void Main()
{
BenchmarkRunner.Run<BoxingPerformance>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment