-
-
Save lgolubyev/9bde3788e1fecfffe26d820e1d94f38f 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.Reflection; | |
namespace ReflectionBenchmarks | |
{ | |
internal class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<InvokeTest>(); | |
} | |
} | |
public class InvokeTest | |
{ | |
private MethodInfo? _method; | |
private object[] _args = new object[1] { 42 }; | |
[GlobalSetup] | |
public void Setup() | |
{ | |
_method = typeof(InvokeTest).GetMethod(nameof(InvokeMe), BindingFlags.Public | BindingFlags.Static)!; | |
} | |
[Benchmark] | |
// *** This went from ~116ns to ~39ns or 3x (66%) faster.*** | |
public void InvokeSimpleMethod() => _method!.Invoke(obj: null, new object[] { 42 }); | |
[Benchmark] | |
// *** This went from ~106ns to ~26ns or 4x (75%) faster. *** | |
public void InvokeSimpleMethodWithCachedArgs() => _method!.Invoke(obj: null, _args); | |
public static int InvokeMe(int i) => i; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment