Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using BenchmarkDotNet.Attributes;
- using BenchmarkDotNet.Running;
- using System;
- using System.Globalization;
- using System.Linq.Expressions;
- using System.Reflection;
- namespace SomeBench
- {
- public class Program
- {
- static void Main()
- {
- BenchmarkRunner.Run<Program>();
- }
- Random _random;
- MethodInfo _invoker;
- Bar _barFunc;
- Bar _barExpressionFunc;
- [GlobalSetup]
- public void GlobalSetup()
- {
- _random = new Random((int)DateTime.Now.Ticks);
- _invoker = typeof(Foo).GetMethod("Bar", BindingFlags.Public | BindingFlags.Static);
- _barFunc = (Bar) Delegate.CreateDelegate(typeof(Bar), _invoker);
- var paramExpr = Expression.Parameter(typeof(int));
- var invokeExpr = Expression.Call(_invoker, paramExpr);
- var lambda = Expression.Lambda<Bar>(invokeExpr, paramExpr);
- _barExpressionFunc = lambda.Compile();
- }
- [Benchmark(Baseline = true)]
- public void DirectCall()
- {
- _ = Foo.Bar(_random.Next());
- }
- [Benchmark]
- public void ReflectionCall()
- {
- _ = (string) _invoker.Invoke(null, new object[] {_random.Next()});
- }
- [Benchmark]
- public void DelegateCall()
- {
- _ = _barFunc(_random.Next());
- }
- [Benchmark]
- public void ExpressionCall()
- {
- _ = _barExpressionFunc(_random.Next());
- }
- }
- public delegate string Bar(int n);
- public class Foo
- {
- public static string Bar(int n) => n.ToString(CultureInfo.InvariantCulture);
- }
- }
- /*
- | Method | Mean | Error | StdDev | Ratio |
- |--------------- |---------:|----------:|----------:|------:|
- | DirectCall | 106.9 ns | 0.1416 ns | 0.1255 ns | 1.00 |
- | ReflectionCall | 287.1 ns | 0.4297 ns | 0.4020 ns | 2.69 |
- | DelegateCall | 109.3 ns | 0.1600 ns | 0.1497 ns | 1.02 |
- | ExpressionCall | 118.7 ns | 0.1811 ns | 0.1694 ns | 1.11 |
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement