Optimizing rulii
rulii 2.2.0 ran about 1.4 million rules a second on one thread. This is the rule:
Rule rule = Rule.builder() .name("freeShippingRule") .given(condition((Integer age, String country) -> age >= 18 && "CA".equals(country))) .then(action((Long total) -> sink += total)) .build();Two comparisons and an addition. An if statement does that hundreds of millions of times a second, so nearly everything in that figure was rulii looking after itself: finding age, country and total among the bindings, handing them over, calling the two lambdas and recording what happened.
rulii 2.3.0 runs the same rule 8.1 million times a second. Nothing changes in your rules, and they accept, reject and report exactly what they did. This post is about where the time was going, what changed, and what we measured and threw away.
The numbers
Section titled “The numbers”Runs per second on one thread, each release as it is on Maven Central:
| What runs | 2.2.0 | 2.3.0 |
|---|---|---|
| A rule: a condition and an action | 1.4 million | 8.1 million |
| A condition with three parameters matched by name | 1.9 million | 9.1 million |
| A rule set of twenty rules | 57,000 | 329,000 |
| A rule set of ten built-in validators | 38,000 | 215,000 |
| A rule flow of five steps | 272,000 | 1.5 million |
A new RuleContext |
766,000 | 2.6 million |
| A condition written as a Java script (Janino) | 1.5 million | 4.2 million |
| A condition written in JavaScript (GraalJS) | 7,700 | 7,900, or 160,000 with context reuse |
A rule set of twenty at 329,000 runs a second is 6.6 million rules a second. The ten validators at 215,000 are 2.1 million checks a second.
Memory went the same way. A rule run allocated 3.5 KB and now allocates 0.5 KB; the rule set of twenty went from 71 KB to 11 KB a run. That’s the part your garbage collector notices.
How to read them. They were measured with JMH on one machine, on JDK 17, on one thread. Except in the RuleContext row the context is built once and kept: twelve bindings in two scopes, the way an application has one for a request. And they measure the engine, not your rules. The rules here do next to nothing, on purpose. If your rule calls a database it will run as fast as your database, in either version.
Behaviour first
Section titled “Behaviour first”A rule engine has one job, which is to do what the rules say. Doing it quickly comes second, so every change had to show that it changed nothing before anybody looked at its numbers.
For the changes at the core that meant three things. The old code and the new code were run side by side over generated cases, and what they produced was compared line by line: results, exception types, messages. Then the whole test suite. Then the test suites of rulii-spring and rulii-bean-validation, run against the changed engine.
For parameter matching, which sits under everything, the comparison ran to 28 million lines, all identical. We also fed it five deliberately broken versions of the change, to find out whether the comparison would notice. It noticed all five.
Where the time went
Section titled “Where the time went”We started with a list of suspects, made by reading the code. It survived about as well as such lists do: the top suspect was guilty, one was innocent, and the worst offender in validation wasn’t on it.
Runs per second after each step. The first and last rows are the releases; the ones in between are development builds, one run each.
| After | A rule set of twenty | Ten validators | A five-step flow |
|---|---|---|---|
| 2.2.0 | 57,000 | 38,000 | 272,000 |
| Read-only arguments made cheap | 65,000 | 44,000 | 292,000 |
| Parameter matching without the lists and the descriptions | 112,000 | 61,000 | 495,000 |
| The method handle adapted once | 243,000 | 84,000 | 991,000 |
| The argument array handed straight to the call | 294,000 | 98,000 | 1.16 million |
| 2.3.0: validators, converters and binding names as well | 329,000 | 215,000 | 1.5 million |
Read-only arguments
Section titled “Read-only arguments”A condition decides; it doesn’t change things. So rulii hands a condition its arguments read-only, and the documentation says so.
That guard had a price, and the quick win was to make it optional. With it switched off, fifteen tests failed, all with the same complaint: a write that should’ve been refused went through. They were right, so the guard stayed on and we went looking for what it cost.
Two things. The argument list was copied on every call, whether or not anything in it needed protecting, and usually nothing does. And every value read through the read-only view built a complete copy of its binding first, which a script pays for on every variable it touches. Now the list is copied only when an argument needs a read-only version, and a value is read where it is. For a rule written in Java, the guard kept on measured within noise of the guard switched off.
Sentences nobody read
Section titled “Sentences nobody read”For every parameter of every call, the engine wrote a sentence explaining how it had matched the parameter to a binding. It’s a good sentence, and it’s useful when a rule doesn’t get the value you expected. Nobody was reading it the other few million times a second. Around it sat a small pile of lists: one per matching strategy, one for the strategies combined, each wrapped to make it unmodifiable.
Now the sentence is written when somebody asks for it, and no list is made when nothing matches. A condition with three named parameters went from about 2 million runs a second to about 5 million, and from 2.9 KB a run to 0.6 KB.
Calling the rule
Section titled “Calling the rule”The most expensive thing the engine did for a rule was call it.
A rule’s method is called through a MethodHandle, with invokeWithArguments. That call is the convenient one: it takes any number of arguments and sorts out the types. On JDK 17 it also builds a new adapter around the handle every time it’s called. Measured on its own, the call ran about 12 million times a second.
The handle is now adapted once, when the rule is built, and after that the same call runs about 300 million times a second. By then it was about half of what a rule cost, so rules got twice as fast in one change.
The argument array
Section titled “The argument array”Arguments were resolved into an array, wrapped in a list, turned back into an array for the call and copied once more on the way in. The array now goes straight through. Thirteen to sixteen percent, for removing three conversions that cancelled each other out.
Validators
Section titled “Validators”In 2.2.0 a built-in validator cost three to four times what a rule did, and it wasn’t on the list of suspects. Validators.notNull(binding("name")) read name through the engine’s whole function pipeline, parameter matching included, and did so twice for each validator. It now reads the binding. Ten validators went from 98,000 runs a second to more than 200,000.
Building a context
Section titled “Building a context”We expected the cost of a new RuleContext to be spread across all the services it sets up. It wasn’t. More than half of it was one of them: every new context created the eighteen built-in type converters, and each converter looked up its own generic types by reflection, in case they’d changed since the last context. They hadn’t. The converters are created once now and shared; they have no state.
The other find was the name check. Every binding has its name checked, and the check was a regular expression: a matcher per name, to confirm that age is a valid identifier. A loop over the characters does the same, and agreed with the regular expression on 2.3 million names.
Between them, 766,000 new contexts a second became 2.6 million. That matters most to code that calls rule.run(bindings) and gets a new context each time.
What we measured and didn’t keep
Section titled “What we measured and didn’t keep”- Skipping the tracer when nobody is listening. No difference worth having. The JIT compiler had already worked that out.
- Plain reflection instead of method handles. Just as fast on JDK 17. It also changed the exception a caller sees in 469 of 1,018 test calls, mostly when an argument has the wrong type. Out.
- Passing more than four arguments directly. Built, measured, no better than the adapter. Four stayed four.
- Switching the read-only guard off. See above. Fifteen tests.
JavaScript
Section titled “JavaScript”The odd row in the first table is GraalJS: about 7,900 evaluations a second, in both releases, whatever the script says.
The script is ctx.age >= 18, and on its own it takes about a microsecond. But every evaluation ran in a JavaScript context created for it and closed after it, and creating a context takes more than a hundred times as long as the script. That isolation is worth something, since one script can’t leave anything behind for the next. It’s also nearly all of the bill.
Several ways around it didn’t survive:
- Reuse a context and run the script in it as it is. A script with a top-level
letfails the second time: already declared. - Give each
RuleContextits own JavaScript context and let the garbage collector close it. Fine on one thread. On eight, with a 512 MB heap, contexts were created faster than they were collected, and three runs out of five ended in anOutOfMemoryError. - Check after each script whether it changed a built-in. The check costs more than a new context.
- Freeze the built-ins. Then
o.toString = ...quietly does nothing, in scripts that were minding their own business.
What 2.3.0 has is a pool of contexts, and it’s opt-in. The script runs inside a function, so what it declares ends with it, and a global it leaves behind is removed before the context is used again. The one thing not undone is a change made inside a built-in (String.prototype.shout = ...), which is why you have to ask for it. If you do, the same condition runs about 160,000 times a second. See Scripting Support.
Bean Validation
Section titled “Bean Validation”rulii-bean-validation 1.0.0 turned every constraint into a rule and ran it through the engine. For @NotNull on a field that’s a lot of ceremony around one comparison.
In 1.1.0 a constraint backed by one of rulii’s own validators is asked directly, and a class with nothing but such constraints is validated without bindings or a rule flow. Anything that is a rulii feature (@Expr, @Validate, a custom ConstraintValidator) still runs in the engine. Validations per second on one thread:
| What is validated | 1.0.0 on rulii 2.2.0 | 1.1.0 on rulii 2.3.0 |
|---|---|---|
| A bean of ten satisfied constraints | 34,000 | 640,000 |
| The same bean with three violations | 27,000 | 160,000 |
| An order cascading into ten lines | 4,400 | 120,000 |
| An order cascading into a hundred lines | 590 | 23,000 |
A bean with one custom ConstraintValidator |
220,000 | 800,000 |
Part of that is the engine getting faster underneath; the larger part is not going through the engine at all. The details are in the 1.1.0 release notes.
What’s left
Section titled “What’s left”A condition with no parameters runs 75 million times a second. Give it three named parameters and it runs 9 million times. So most of what a rule costs now is the engine working out which binding goes into which parameter, on every call, although the answer is nearly always the same as last time.
That’s the next thing.