1

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

Mukesh Gupta
  • 59
  • 1
  • 7
  • Can you provide the full code for the fast aswell as the slow situation? – thehennyy Jul 20 '19 at 12:47
  • @thehennyy this is the actual code which i'm trying to run just say you remove convert.todatetime and assume it as a string comparison it compile code much faster then this – Mukesh Gupta Jul 21 '19 at 16:08
  • Ok I can see the slight higher runtime using Date functions aswell. I do not think you can do much about this, maybe have a look at roslyn, expression trees or other libraries to handle user given expressions. – thehennyy Jul 22 '19 at 06:24
  • @thehennyy can you help me with some example or any other third party libraries, my requirement is user can create any formula conditional,calculation or some custom function like datediff,datepart – Mukesh Gupta Jul 22 '19 at 08:08
  • Sorry I did not have such requirements in past and do not have a overview of this field. If the overhead of a few milliseconds is actually a problem you may can gain reliefe by introducing a cache. – thehennyy Jul 22 '19 at 08:54

0 Answers0