jeudi 2 avril 2020

C# Reflection performance comparison when invoking class with parameter

I have heard a lot about Linq Expression performance. But wasn't able to check it myself. Please take a look on the next .NET Core app example:

 class Program
    {
        static void Main(string[] args)
        {
            var classType = Type.GetType("ConsoleApp1.TestClass");
            var classConstructor = classType.GetConstructor(new[] { typeof(string) });

            //var param = Expression.Parameter(typeof(string));
            //var newExpression = Expression.New(classConstructor, param);
            //LambdaExpression lambda = Expression.Lambda(newExpression, param);
            //var compiled = lambda.Compile();
            //var instance = compiled.DynamicInvoke("test");

            //var instance = Activator.CreateInstance(classType, "test");

            //var instance = classConstructor.Invoke(new object[] { "test" });

            Console.ReadLine();
        }
    }

    class TestClass
    {
        public TestClass(string param)
        {

        }
    }

When I am running this code with Expression version uncommented then code works 10 times slower. Please advice what could be wrong or it is as expected.





Aucun commentaire:

Enregistrer un commentaire