How to improve compile time using CSharpCodeProvider

旧时模样 提交于 2019-12-23 02:19:12

问题


I have an application where user can create its own formula it works fine for all case but when i have DateTime Fields in my formula the compilation part of the code take around 132 ms for one formula where at the same time i have 31 formula each with different value.

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;

namespace abc
{
    public class Abc
    {
        static void Main()
        {
            var code = @"
using System;
namespace First
{
    public class program
    {
        public static int Main()
        {
            if(Convert.ToDateTime(""01-04-2019 10:25:00"")>Convert.ToDateTime(""01-04-2019 15:00:00""))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }
}";
            Console.WriteLine(code);
            var options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = false;
            var provider = new CSharpCodeProvider();
            var compile = provider.CompileAssemblyFromSource(options, code);
            var type = compile.CompiledAssembly.GetType("First.program");
            var abc = Activator.CreateInstance(type);

            var method = type.GetMethod("Main");
            var result = method.Invoke(abc, null);

            Console.WriteLine(result); //output: abc
        }
    }
}

At this point var compile = provider.CompileAssemblyFromSource(options, code); It takes 132 ms but if don't use any date fields it takes 1 ms

来源:https://stackoverflow.com/questions/57122941/how-to-improve-compile-time-using-csharpcodeprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!