Search code examples
drools

Why does the order of how we specify the variables in a '==' comparison matter?


What i noticed is that there is a big performance difference by just changing the order of the variables that are compared with the '==' operator. For example $variable == variable is considerably slower than variable == $variable. Why is this so and are there similar cases like this one?

By the way i am using a version of OptaPlanner from GitHub downloaded from GitHub that uses the "7.0.0-SNAPSHOT" Drools version.

This is the case in all the rules that do a cross product where i try to match variables from one pattern in another. For example:

rule "Example"
   when
       Class1(... , $var : var)
       Class2($var == var, ...)
   then
end

So when i changed the expression $var == var to var == $var immediately i could spot the difference.

When it comes to benchmarking at first i just compared this in one rule that i was focused on, so i only did this type of change in the expressions there(the other rules were deleted). Afterwards i applied this to all the rules.


Solution

  • I think what happens is that

    Class1(... , $var : var)
    Class2(var == $var, ...)
    

    produces a network where all Class1 facts are taken, and then the Cartesian product with all Class2 facts with identical var field is created.

    In contrast,

    Class1(... , $var : var)
    Class2($var == var, ...)
    

    "rewritten" by the compiler as

    Class1(... , $var : var)
    $c2: Class2(...)
    eval( $var == $c2.var )
    

    creates the Cartesian product of all Class1 facts and all (!) Class2 facts and only thereafter filters all where the eval is false.

    The traditional syntax (Drools 5 and earlier) forced you to have the field name on the left-hand side; only later on (late 5.x, 6.x), any logical expression was permitted.

    After speaking to s.o. from the Drools team, a more accurate description might be this:- It is likely that where an attribute is compared to something else an optimization is triggered. Someone from the Drools team will take a look and possibly improve it by checking also the reversed expression.