Created
April 21, 2018 05:11
-
-
Save ufcpp/0fd6fa47d05a21ad7fb559a615cd0460 to your computer and use it in GitHub Desktop.
ボックス化によるパフォーマンスへの影響
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; | |
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