Caching Expressions Using Parser Caches

Caching Expressions Using Parser Caches

The ExpressionLanguage component already provides a compile() method to be able to cache the expressions in plain PHP. But internally, the component also caches the parsed expressions, so duplicated expressions can be compiled/evaluated quicker.

The Workflow

Both evaluate() and compile() need to do some things before each can provide the return values. For evaluate(), this overhead is even bigger.

Both methods need to tokenize and parse the expression. This is done by the parse() method. It returns a ParsedExpression. Now, the compile() method just returns the string conversion of this object. The evaluate() method needs to loop through the "nodes" (pieces of an expression saved in the ParsedExpression) and evaluate them on the fly.

To save time, the ExpressionLanguage caches the ParsedExpression so it can skip the tokenize and parse steps with duplicate expressions. The caching is done by a PSR-6 CacheItemPoolInterface instance (by default, it uses an ArrayAdapter). You can customize this by creating a custom cache pool or using one of the available ones and injecting this using the constructor:

1
2
3
4
5
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Cache\Adapter\RedisAdapter;

$cache = new RedisAdapter(...);
$language = new ExpressionLanguage($cache);

New in version 3.2: PSR-6 caching support was introduced in Symfony 3.2. Prior to version 3.2, a ParserCacheInterface instance had to be injected.

See the The Cache Component documentation for more information about available cache adapters.

Using Parsed and Serialized Expressions

Both evaluate() and compile() can handle ParsedExpression and SerializedParsedExpression:

1
2
3
4
5
6
// ...

// the parse() method returns a ParsedExpression
$expression = $language->parse('1 + 4', array());

var_dump($language->evaluate($expression)); // prints 5
1
2
3
4
5
6
7
8
9
use Symfony\Component\ExpressionLanguage\SerializedParsedExpression;
// ...

$expression = new SerializedParsedExpression(
    '1 + 4',
    serialize($language->parse('1 + 4', array())->getNodes())
);

var_dump($language->evaluate($expression)); // prints 5

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.