-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathResultCreationBenchmark.cs
More file actions
77 lines (65 loc) · 2.52 KB
/
ResultCreationBenchmark.cs
File metadata and controls
77 lines (65 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Collections.Concurrent;
using System.Globalization;
using System.Net;
using System.Reflection;
using BenchmarkDotNet.Attributes;
namespace ManagedCode.Communication.Benchmark;
[MemoryDiagnoser]
[SimpleJob(warmupCount: 3, iterationCount: 10)]
public class ResultCreationBenchmark
{
private static readonly Exception TestException = new InvalidOperationException("Benchmark test");
private static readonly Type ResultIntType = typeof(Result<int>);
private static readonly ConcurrentDictionary<Type, MethodInfo> MethodCache = new();
private readonly Exception _exception = TestException;
private readonly object[] _exceptionArray = new object[1];
private MethodInfo _cachedMethod = null!;
[GlobalSetup]
public void Setup()
{
_cachedMethod = ResultIntType.GetMethod(nameof(Result.Fail), [typeof(Exception), typeof(HttpStatusCode)])!;
MethodCache[ResultIntType] = _cachedMethod;
_exceptionArray[0] = TestException;
}
[Benchmark(Baseline = true)]
public Result<int> DirectCall()
{
return Result<int>.Fail(TestException);
}
[Benchmark]
public object Reflection_FindMethodEveryTime()
{
var method = ResultIntType.GetMethod(nameof(Result.Fail), [typeof(Exception), typeof(HttpStatusCode)]);
return method!.Invoke(null, [TestException, HttpStatusCode.InternalServerError])!;
}
[Benchmark]
public object Reflection_CachedMethod()
{
return _cachedMethod.Invoke(null, [TestException, HttpStatusCode.InternalServerError])!;
}
[Benchmark]
public object Reflection_CachedMethod_ReuseArray()
{
// Can't reuse array because we need 2 parameters
return _cachedMethod.Invoke(null, [TestException, HttpStatusCode.InternalServerError])!;
}
[Benchmark]
public object Reflection_ConcurrentDictionary()
{
var method = MethodCache.GetOrAdd(ResultIntType, type => type.GetMethod(nameof(Result.Fail), [typeof(Exception), typeof(HttpStatusCode)])!);
return method.Invoke(null, [TestException, HttpStatusCode.InternalServerError])!;
}
[Benchmark]
public object Activator_TryCreateInstance()
{
var result = Activator.CreateInstance(ResultIntType);
return result!;
}
[Benchmark]
public object Activator_WithPropertySet()
{
var resultType = Activator.CreateInstance(ResultIntType, BindingFlags.NonPublic | BindingFlags.Instance, null, [TestException],
CultureInfo.CurrentCulture);
return resultType!;
}
}