Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using BenchmarkDotNet.Attributes;
- using BenchmarkDotNet.Running;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Dynamic;
- using System.Reflection;
- using static System.Linq.Expressions.Expression;
- class Test
- {
- public int Method(string arg) => 0;
- }
- public class InvokeBenchmark
- {
- private static Func<string, object> _methodInfoInvoke;
- private static Func<string, object> _delegateDynamicInvoke;
- private static Func<string, object> _expressionCompile;
- static InvokeBenchmark()
- {
- var m = typeof(Test).GetMethod("Method");
- var instance = new Test();
- _methodInfoInvoke = value => m.Invoke(instance, new object[] { value });
- var d = m.CreateDelegate(typeof(Func<string, int>), instance);
- _delegateDynamicInvoke = value => d.DynamicInvoke(new object[] { value });
- var x = Variable(typeof(string), "value");
- _expressionCompile = Lambda<Func<string, object>>(
- Convert(
- Call(Constant(instance), m, x), // static メソッドだと第1引数要らない
- typeof(object)
- )
- , x).Compile();
- }
- const int Loops = 1000;
- [Benchmark]
- public void MethodInfoInvoke()
- {
- var sum = 0;
- for (int i = 0; i < Loops; i++)
- {
- sum += (int)_methodInfoInvoke("abc");
- }
- }
- [Benchmark]
- public void DelegateDynamicInvoke()
- {
- var sum = 0;
- for (int i = 0; i < Loops; i++)
- {
- sum += (int)_delegateDynamicInvoke("abc");
- }
- }
- [Benchmark]
- public void ExpressionCompile()
- {
- var sum = 0;
- for (int i = 0; i < Loops; i++)
- {
- sum += (int)_expressionCompile("abc");
- }
- }
- }
- class Program
- {
- static void Main()
- {
- BenchmarkRunner.Run<InvokeBenchmark>();
- }
- }
Add Comment
Please, Sign In to add comment