Table of Contents

Caching

When Evaluate() is called on an expression, it is parsed once. If the same expression is reused the parse is not executed again. Thus, you can reuse Expression instances by changing the parameters, and you will gain in performance because only the traversal of the expression tree will be done.

Moreover, each parsed expression is cached internally, which means you don't even have to care about reusing an Expression instance, the framework will do it for you. The cache is automatically cleaned like the GC does when an Expression is no more used, or memory is needed (i.e. using WeakReference).

You can disable this behavior at the framework level by adding <xref:NCalc.Core.ExpressionOptions.NoCache> at your global expression context.

 MyContext.Value.Options = ExpressionOptions.NoCache;

You can also tell a specific Expression instance not to be taken from the cache.

 var expression = new Expression("1 + 1", ExpressionOptions.NoCache);

You can customize the cache implementation using Dependency Injection.