Search code examples
dynamic-expresso

DynamicExpresso Eval memory leak


Is there a solution to avoid memory leak in a simple expression evaluation like this ?

        inter.SetVariable("tick", tick++);
        if (inter.Eval<bool>("(tick%2)==1"))
        {
            odd++;
            if ((odd % 100) == 0)
                System.GC.Collect();
        }
        else
            even++;

I'm running this code periodically in a WinForm application on a Linux machine with Mono (5.0.1.1) and the memory usage continuously increase. Tested on Windows the Process.WorkingSet64 was increasing with a lower rate than Linux. The GC.GetTotalMemory is always stable.


Solution

  • If possible, it is better to use the Parse method and then just Invoke the expression multiple times.

    Something like:

    // One time only
    string expression = "(tick%2)==1";
    Lambda parsedExpression = interpreter.Parse(expression, new Parameter("tick", typeof(int)));
    
    // Call invoke for each cycle...
    var result = parsedExpression.Invoke(tick++);
    

    But from my previous tests I don't have see any Memory Leak, are you sure that is this the problem?