json-logic-php
json-logic-php copied to clipboard
optimized apply() by moving $operators into a static array where possible
Moved most of $operators -array's content into a static variable, so the array doesn't need to be defined on each call to apply().
Operators for var, missing and missing_some were crudely moved into the if/elseif/else structure as those needed use ($data). Their implementation in the if/elseif/else could probably be prettier.
Rationale for this change was performance. In our application we needed to run n-amounts of apply() calls to potentially thousands, sometimes tens of thousands of arrays, and it quickly became apparent that there was some room for optimization. After moving the $operators as static, the apply() -calls only used 1/3rd of the time they used to.
In my (crude) tests, with 100k loops for these test logics and data
$loops = 100000;
$logics = [
[
"and" => [
['var' => 'dummy'],
]
],
[
"and" => [
['var' => 'foo'],
['var' => 'foo']
]
],
[
'+' => [
['var' => 'foo'],
['var' => 'foo']
]
],
[
'missing' => 'foo'
]
];
$data = [
'foo' => 11,
'bar' => 127,
'dummy' => 'foobar'
];
$org_start = microtime(true);
for($i = 0; $i <= $loops; $i++)
{
foreach($logics as $logic)
{
\JWadhams\JsonLogic::apply($logic, $data);
}
}
$org_end = microtime(true) - $org_start;
$opt_start = microtime(true);
for($i = 0; $i <= $loops; $i++)
{
foreach($logics as $logic)
{
\JSLOma::apply($logic, $data);
}
}
$opt_end = microtime(true) - $opt_start;
var_export([
'jsl' => $org_end,
'oma' => $opt_end,
]);
array (
'jsl' => 1.6032569408416748,
'oma' => 0.42403507232666016,
)
The "static operations" version performed in 1/4th of the time the current 1.5.1 version does. This was with opcache enabled on php.