Increase the Performance of Rules by Declaring Variables in the Right Order

Increase the Performance of Rules by Declaring Element Variables in the Right Order

Element variables are dynamic placeholders for graph elements. If you declare two element variables in the left-hand side of your rule, pay attention to the order in which you declare them! The right order can increase the performance of rules notably. GrGen always loops over the last declared variable first. Let us have a look at two code examples to understand what that means. We can already state that the second code example will have a better performance, as will be explained later.

Code Example 1:

rule perfTestRule {
p1:Product;
p2:Product;
if{ p1.name == "Test"; }
modify {
emit("Cool!\n");
}
}

Code Example 2:

rule perfTest2Rule {
p2:Product;
p1:Product;
if{ p1.name == "Test"; }
modify {
emit("Cool!\n");
}
}

The only difference between the two rules is that in code example 2 p2 is declared first, followed by p1. Code example 1 declares the variables the other way around. If we look at the if condition we can see that we want to filter for specific p1 elements. As the last declared variable is looped first, the second rule is faster. In the first version, the compiler will always pick a node for p2 first, which is unrestricted, and then pick a node for p1 and check if the if condition holds. That basically results in three operations: node lookup, node lookup and condition check. In the second version, it will pick p1, check the if condition, and only if it is true pick a node for p2. Therefore, the second version can save many node lookup operations, resulting in a better performance.

Keep this in mind when you write rules that apply to big graph files and are experiencing performance issues. Further, have a look at the other options to increase the performance described in this knowledge base category.

Was this article helpful?

Related Articles