Fast Dynamic Expressions (not named)

Nov 16, 2007 at 5:17 PM
Edited Nov 16, 2007 at 8:59 PM
HI Eugene,

We're scouring the code looking for a way to execute an "unnamed" expression. For instance, is it possible to just execute something like this:

engine.GetResult("A + B");

The only way we can see how to do it is to add a named expression (by setting the ExpressionName on the ExpressionContext object) and then removing it. We tried adding a temporary named expression with a random name. The problem is that adding and removing in a loop is super slow.

Our experiments seem to indicate that a lot of the time is in parsing and checking dependencies, etc.

Can you give us an idea of how to work around this, or consider adding a way to do it? It seems like the code should be able to access the table of expressions even if the expression doesn't have a name.

We acknowledge that this might be an impossibility. You have to parse and compile the code to run it. We will likely change our application so the "unnamed" expressions are pre-loaded as "named" expressions.

Nov 16, 2007 at 9:45 PM
Hi Dustin,

Are you looking for a way to do quick evals using names in the calculation engine or a way to add expressions to the engine without giving them a name (similar to external references in the FormulaEngine)?
Nov 16, 2007 at 9:59 PM
We would like to add expressions to the engine without giving them a name. In our model, they could reference other named expressions, but nothing would ever
reference them.

This is how I did it for now:

            string temporaryName = Guid.NewGuid().ToString();
            // wraps Eugene's code: creates an ExpressionContext, adds it to the engine, etc
            AddExpression(temporaryName, expression.Value);
            decimal result = Convert.ToDecimal(engine.GetResult(temporaryName));
           // really just a call to engine.RemoveExpression(...)
            return result;

What we really want is magic. We want to run many, many "unnamed" expressions quickly at runtime. The problem is that parsing and compiling takes time and we were trying to skip the step of pre-loading the engine so it compiles.

As I mentioned, I think we're better off pre-loading all our expressions in advance and give them names. This isn't a problem for us I don't think. When I originally wrote my message we thought we were getting that for free with FormulaEngine. We traced your code and realized that ExpressionFactory.CreateDynamic compiles the code, and that's why calling it in a loop 10000 times doesn't give us nice results.

Thanks for your patience.