Moritz Lenz >
Math-Expression-Evaluator >
Math::Expression::Evaluator::Optimizer

Math::Expression::Evaluator::Optimizer - Optimize Math::Expression::Evaluator ASTs

use Math::Expression::Evaluator; my $m = Math::Expression::Evaluator->new("2 + 4*f"); $m->optimize(); for (0..100){ print $m->val({f => $_}), "\n"; }

Math::Expression::Evaluator::Optimizer performs simple optimizations on the abstract syntax tree from Math::Expression::Evaluator.

You should not use this module directly, but interface it via Math::Expression::Evaluator.

The following optimizations are implemented:

- Constant sub expressions:
`variable + 3 * 4`

is simplfied to`variable + 12`

. - Joining of constants in mixed constant/variable expressions:
`2 + var + 3`

is simplified to`var + 5`

. Works only with sums and products (but internally a`2 - 3 + x`

is represented as`2 + (-3) + x`

, so it actually works with differences and divisions as well). - Flattening of nested sub expression:
`a * (3 * b)`

is flattened into`a * 3 * b`

. Currently this is done before any other optimization and not repeated.

`optimize()`

currently takes two full loops through the AST, copying and recreating it. If you execute `val()`

only once, calling `optimize()`

is in fact a performance loss.

If the expression is optimizable, and you execute it `$n`

times, you usually have a net gain over unoptimized execution if `$n > 15`

.

Of course that value depends on the complexity of the expression, and how well it can be reduced by the implemented optimizations.

Your best is to always benchmark what you do. Most of the time the compiled version returned by `->compiled`

is much faster than the optimized (and not compiled) form.

syntax highlighting: