Skip to content

Instantly share code, notes, and snippets.

@jcansdale
Created September 9, 2016 13:54
Show Gist options
  • Save jcansdale/e48ee0ae85970d8176d0bc22e24dadb8 to your computer and use it in GitHub Desktop.
Save jcansdale/e48ee0ae85970d8176d0bc22e24dadb8 to your computer and use it in GitHub Desktop.
Compile vs manual evaluation
Host Process Environment Information:
BenchmarkDotNet.Core=v0.9.9.0
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4500U CPU 1.80GHz, ProcessorCount=4
Frequency=2338341 ticks, Resolution=427.6536 ns, Timer=TSC
CLR=MS.NET 4.0.30319.42000, Arch=32-bit ?
GC=Concurrent Workstation
JitModules=clrjit-v4.6.1586.0

Type=ExpressionInvokerBenchmark  Mode=Throughput  LaunchCount=1  
WarmupCount=3  TargetCount=3  
                               Method |         Median |      StdDev |            Min |            Max |

----------------------------------------- |--------------- |------------ |--------------- |--------------- | ConstantExpression_Compile_DynamicInvoke | 29,533.4651 ns | 837.8480 ns | 28,759.7674 ns | 30,433.8659 ns | ConstantExpression_Value | 12.5724 ns | 0.0746 ns | 12.4984 ns | 12.6476 ns |

    [MinColumn, MaxColumn]
    public class ExpressionInvokerBenchmark
    {
        Expression<Action> expression  = () => StaticClass.StaticMethod(666);

        [Benchmark]
        public object ConstantExpression_Compile_DynamicInvoke()
        {
            var methodCallExpression = (MethodCallExpression)expression.Body;
            var constantExpression = (ConstantExpression)methodCallExpression.Arguments[0];
            var lambdaExpression = Expression.Lambda(constantExpression);
            var dele = lambdaExpression.Compile();
            return dele.DynamicInvoke();
        }

        [Benchmark]
        public object ConstantExpression_Value()
        {
            var methodCallExpression = (MethodCallExpression)expression.Body;
            var constantExpression = (ConstantExpression)methodCallExpression.Arguments[0];
            return constantExpression.Value;
        }

        class StaticClass
        {
            public static void StaticMethod(int i)
            {
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment