Guest User

Untitled

a guest
Feb 24th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. using BenchmarkDotNet.Attributes;
  2. using BenchmarkDotNet.Running;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Dynamic;
  7. using System.Reflection;
  8. using static System.Linq.Expressions.Expression;
  9.  
  10. class Test
  11. {
  12. public int Method(string arg) => 0;
  13. }
  14.  
  15. public class InvokeBenchmark
  16. {
  17. private static Func<string, object> _methodInfoInvoke;
  18. private static Func<string, object> _delegateDynamicInvoke;
  19. private static Func<string, object> _expressionCompile;
  20.  
  21. static InvokeBenchmark()
  22. {
  23. var m = typeof(Test).GetMethod("Method");
  24. var instance = new Test();
  25.  
  26. _methodInfoInvoke = value => m.Invoke(instance, new object[] { value });
  27.  
  28. var d = m.CreateDelegate(typeof(Func<string, int>), instance);
  29. _delegateDynamicInvoke = value => d.DynamicInvoke(new object[] { value });
  30.  
  31. var x = Variable(typeof(string), "value");
  32. _expressionCompile = Lambda<Func<string, object>>(
  33. Convert(
  34. Call(Constant(instance), m, x), // static メソッドだと第1引数要らない
  35. typeof(object)
  36. )
  37. , x).Compile();
  38. }
  39.  
  40. const int Loops = 1000;
  41.  
  42. [Benchmark]
  43. public void MethodInfoInvoke()
  44. {
  45. var sum = 0;
  46. for (int i = 0; i < Loops; i++)
  47. {
  48. sum += (int)_methodInfoInvoke("abc");
  49. }
  50. }
  51.  
  52. [Benchmark]
  53. public void DelegateDynamicInvoke()
  54. {
  55. var sum = 0;
  56. for (int i = 0; i < Loops; i++)
  57. {
  58. sum += (int)_delegateDynamicInvoke("abc");
  59. }
  60. }
  61.  
  62. [Benchmark]
  63. public void ExpressionCompile()
  64. {
  65. var sum = 0;
  66. for (int i = 0; i < Loops; i++)
  67. {
  68. sum += (int)_expressionCompile("abc");
  69. }
  70. }
  71. }
  72.  
  73. class Program
  74. {
  75. static void Main()
  76. {
  77. BenchmarkRunner.Run<InvokeBenchmark>();
  78. }
  79. }
Add Comment
Please, Sign In to add comment