Advertisement
Guest User

Untitled

a guest
Aug 6th, 2021
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. using BenchmarkDotNet.Attributes;
  2. using BenchmarkDotNet.Running;
  3. using System;
  4. using System.Globalization;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7.  
  8. namespace SomeBench
  9. {
  10.   public class Program
  11.   {
  12.     static void Main()
  13.     {
  14.       BenchmarkRunner.Run<Program>();
  15.     }
  16.  
  17.     Random _random;
  18.     MethodInfo _invoker;
  19.     Bar _barFunc;
  20.     Bar _barExpressionFunc;
  21.     [GlobalSetup]
  22.     public void GlobalSetup()
  23.     {
  24.       _random = new Random((int)DateTime.Now.Ticks);
  25.       _invoker = typeof(Foo).GetMethod("Bar", BindingFlags.Public | BindingFlags.Static);
  26.       _barFunc = (Bar) Delegate.CreateDelegate(typeof(Bar), _invoker);
  27.       var paramExpr = Expression.Parameter(typeof(int));
  28.       var invokeExpr = Expression.Call(_invoker, paramExpr);
  29.       var lambda = Expression.Lambda<Bar>(invokeExpr, paramExpr);
  30.       _barExpressionFunc = lambda.Compile();
  31.     }
  32.  
  33.     [Benchmark(Baseline = true)]
  34.     public void DirectCall()
  35.     {
  36.       _ = Foo.Bar(_random.Next());
  37.     }
  38.  
  39.     [Benchmark]
  40.     public void ReflectionCall()
  41.     {
  42.       _ = (string) _invoker.Invoke(null, new object[] {_random.Next()});
  43.     }
  44.  
  45.     [Benchmark]
  46.     public void DelegateCall()
  47.     {
  48.       _ = _barFunc(_random.Next());
  49.     }
  50.  
  51.     [Benchmark]
  52.     public void ExpressionCall()
  53.     {
  54.       _ = _barExpressionFunc(_random.Next());
  55.     }
  56.   }
  57.  
  58.   public delegate string Bar(int n);
  59.  
  60.   public class Foo
  61.   {
  62.     public static string Bar(int n) => n.ToString(CultureInfo.InvariantCulture);
  63.   }
  64. }
  65.  
  66. /*
  67. |         Method |     Mean |     Error |    StdDev | Ratio |
  68. |--------------- |---------:|----------:|----------:|------:|
  69. |     DirectCall | 106.9 ns | 0.1416 ns | 0.1255 ns |  1.00 |
  70. | ReflectionCall | 287.1 ns | 0.4297 ns | 0.4020 ns |  2.69 |
  71. |   DelegateCall | 109.3 ns | 0.1600 ns | 0.1497 ns |  1.02 |
  72. | ExpressionCall | 118.7 ns | 0.1811 ns | 0.1694 ns |  1.11 |
  73. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement