Home

Awesome

NCalc

Build status NuGet NuGet

:warning: This repository is currently only passively maintained. If there are fully fledged PRs, I will occasional merge those in and publish new versions. If you would like to become a maintainer and work on some of the open issues, please reply here https://github.com/sklose/NCalc2/issues/61

A clone of NCalc from http://ncalc.codeplex.com/ with the following changes:

Installation

Simply install the package via NuGet

PM> Install-Package CoreCLR-NCalc

Creating Lambdas

Simple Expressions

var expr = new Expression("1 + 2");
Func<int> f = expr.ToLambda<int>();
Console.WriteLine(f()); // will print 3

Expressions with Functions and Parameters

class ExpressionContext
{
  public int Param1 { get; set; }
  public string Param2 { get; set; }
  
  public int Foo(int a, int b)
  {
    return a + b;
  }
}

var expr = new Expression("Foo([Param1], 2) = 4 && [Param2] = 'test'");
Func<ExpressionContext, bool> f = expr.ToLambda<ExpressionContext, bool>();

var context = new ExpressionContext { Param1 = 2, Param2 = "test" };
Console.WriteLine(f(context)); // will print True

Performance Comparison

The measurements were done during CI runs on AppVeyor and fluctuate a lot in between runs, but the speedup is consistently in the thousands of percent range. The speedup measured on actual hardware was even higher (between 10,000% and 35,000%).

FormulaDescriptionExpression Evaluations / secLambda Evaluations / secSpeedup
(4 * 12 / 7) + ((9 * 2) % 8)Simple Arithmetics474,247.8732,691,490.416,793.33%
5 * 2 = 2 * 5 && (1 / 3.0) * 3 = 1Simple Arithmetics276,226.3193,222,709.0533,648.67%
[Param1] * 7 + [Param2]Constant Values707,493.2721,766,101.472,976.51%
[Param1] * 7 + [Param2]Dynamic Values582,832.1021,400,445.133,571.80%
Foo([Param1] * 7, [Param2])Dynamic Values and Function Call594,259.6917,209,334.342,795.93%