Skip to content

Conversation

tapsavo
Copy link

@tapsavo tapsavo commented Dec 2, 2024

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.

…ible. Operations which 'use $data' were moved into the if/elseif/else structure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant