Newshot

Swapping Jolt's sorted collections to a B+tree

Original text(via Lobsters)

Swapping Jolt's sorted collections to a B+tree

Until recently, sorted-map and sorted-set in Jolt were a straight port of Clojure's PersistentTreeMap, which is backed by a persistent red-black tree. Using a red-black tree has worked well for Clojure, and it provides a solid foundation for backing these data structures. However, red-black trees have a downside, which is that every entry gets its own small node, meaning that every step of a lookup follows a pointer to a different place in memory.

So, naturally I got curious to see if a different data structure could be used for the same job which might have a lower overhead. Turns out that a red-black tree can indeed be swapped out for a B+tree here. I updated Jolt's sorted collections along with the java.util.TreeMap and TreeSet shims to use a persistent B+tree, which dropped peak memory by 40% while making most operations faster at every size, as we'll see later in the benchmarks.

What was wrong with the red-black tree

Each red-black node in Jolt was a five-slot Scheme vector holding a color along with the key, the value, and its two children. And all that translates into 48 bytes of metadata per entry on top of the key and value themselves. A map with 4 million entries needs a tree around 22 levels deep, so, a lookup can end up visiting about 22 nodes scattered across the heap. And once the tree outgrows the CPU cache, each of these visits is likely to be a cache miss as well.

As you might've guessed, writes also have a similar problem. Since a persistent tree can't modify a node in place, an assoc has to copy every node on the path from the root to the change, which results in 22 small allocations followed by rebalancing at that size.

The B+tree

The key advantage of using a B+tree is that it keeps data in leaves of up to 16 entries and branches through inner nodes of up to 32 children with each node being a single Scheme vector. In this layout, a leaf is written as #(#t k0 v0 k1 v1 ...) with keys and values sitting side by side in one contiguous block. An inner node also stores the largest key below it right next to each child.

Now, the same tree of 4 million entries becomes just 5 levels deep instead of 22. On top of that, a lookup within each node has to only search through adjacent slots that are already in cache. Writes still have to copy the path from the root, but that's now a quarter of the work with each one being copied as a block.

Unsurprisingly, memory use improved significantly, since a full leaf holds 16 entries in 34 machine words, needing only 17 bytes per entry against the red-black tree's 48. Nodes are also allowed to drop to half before they merge, so 34 bytes per entry ends up being the worst case here. It would be ideal to keep the common case near full as much as possible, and a trick that can be used here is to start a fresh node when append goes past either end of the tree rather than splitting a full node into two half-empty ones. A common case for this would be building from ascending keys, which ends up packing every node using this approach. Similarly, deletes end up borrowing entries from a neighbour or merging with it to keep the tree balanced without needing rotations.

The catch

Of course, nothing in life is free, and B+trees do have a weakness of their own. While they're much faster for large collections, building small ones of tens to hundreds of entries one insert at a time ended up being around 15% slower than the red-black tree. The reason goes back to the respective structure of each data structure. Once a map has 17 entries, that requires a root with two leaves, and every insert needs to copy the whole path. So, at smaller sizes the B+tree has to move more bytes per insert than the red-black tree, which is the trade-off.

The numbers

Luckily, there is a way around the problem by changing how collections get built. We can first collect the inputs for into, the sorted-map and sorted-set constructors, and multi-argument conj/assoc to check whether they're already in order, then skip the sort if they are. Additionally, we can drop duplicate keys by keeping the first key along with the last value, which allows us to bulk-load the leaves. The batches can now get merged with the collection that already has entries. Meanwhile, small sources of 8 or fewer entries that go into an empty collection continue to use plain conj, because the overhead of buffering would end up costing more than it actually saves. With these changes in place, the worst remaining case ends up being a 4 entry map at 1.05x, which is effectively as good as a red-black tree.

So, now that we've discussed how B+trees work, and what makes them a good alternative to red-black trees in this scenario, let's look at some actual benchmark numbers comparing the two approaches. The numbers were measured using optimized binaries across several runs on an M1 Max with 64 GB. The JVM comparisons use Clojure 1.12.6 on OpenJDK 20. A ratio under 1.0 means the B+tree is faster.

Small collections

Times are for the whole operation over the collection, which includes building it, doing a lookup for every key, removing every key, and replacing every value. Keys are also scrambled to avoid a degenerate sequential case.

entriesbuildget alldissoc allassoc (replace)
4748 → 785 ns (1.05)342 → 257 ns (0.75)752 → 740 ns (0.98)515 → 497 ns (0.97)
162.98 → 3.05 µs (1.02)1.44 → 0.96 µs (0.67)3.16 → 2.87 µs (0.91)2.27 → 2.10 µs (0.92)
325.99 → 6.25 µs (1.04)3.03 → 2.22 µs (0.73)6.80 → 6.47 µs (0.95)5.06 → 5.10 µs (1.01)
6413.2 → 13.4 µs (1.01)6.46 → 4.70 µs (0.73)14.9 → 13.7 µs (0.92)11.4 → 10.6 µs (0.93)
25662.1 → 60.3 µs (0.97)29.7 → 23.0 µs (0.77)72.6 → 62.2 µs (0.86)59.2 → 48.7 µs (0.82)

As we can see, lookups win at every size, by 23 to 33%. Builds and writes stay flat below 64 entries. Notably, even a 4 entry map ends up being a single leaf searched in place, meaning that it doesn't pay for the extra machinery.

20,000 entries, operation by operation

operationmainB+treeratio
get3.95 ms3.41 ms0.86
contains?3.79 ms3.20 ms0.84
get with a custom comparator10.62 ms6.59 ms0.62
dissoc all12.28 ms8.22 ms0.67
disj half6.55 ms4.46 ms0.68
pop-min loop16.38 ms9.98 ms0.61
pop-max loop24.14 ms11.33 ms0.47
seq walk1.15 ms1.02 ms0.89
reduce0.33 ms0.23 ms0.70
reduce-kv3.02 ms0.17 ms0.06
rseq0.34 ms0.23 ms0.68
subseq0.89 ms0.77 ms0.87
subseq, first element only17.34 ms7.14 ms0.41

The reduce-kv result stands out because it's a result of a fix in the new layout. The original red-black tree code built a map entry for every pair going through the generic sequence path. Walking the leaves and passing each key/value pair straight to the function avoids having to allocate memory for each slot. And since the B+tree can seek to a key to start reading from that leaf without having to rebuild a stack of nodes from the root on every call, repeatedly taking the first element of a subseq gets faster as well.

200,000 entries

operationratio
build0.53
get all0.58
dissoc all0.55
assoc (replace)0.60

From here on out we hit a cliff where the cache matters more than anything else.

100,000 to 4 million entries, compared with the JVM

While performance looked good for thousands of elements, it was also important to check what would happen with collections having millions of entries in order to make sure nothing broke or regressed badly at this scale. The following benchmark builds a sorted map and a sorted set from scrambled keys and then runs a mix of operations over them.

operation, 4M entriesmainB+treeJVM Clojure
into (map)2,441 ms1,841 ms1,659 ms
into (set)2,049 ms1,619 ms2,489 ms
assoc loop2,375 ms2,153 ms1,762 ms
get all777 ms660 ms449 ms
contains? all1,004 ms659 ms615 ms
dissoc half2,520 ms1,662 ms1,098 ms
seq walk171 ms131 ms289 ms
reduce over set63 ms47 ms113 ms
subseq, 1,000 entries0.1 ms0.1 ms0.4 ms

And the good news is that every operation at this scale is also faster than the previous version. Not only that, but Jolt is now faster than the JVM at building sets, walking, reducing, and range queries, while the two are roughly even on contains? and the map build. Finally, point lookups and deletes are still about 1.5x slower than the JVM, which uses a red-black tree backed PersistentTreeMap thanks to the magic of the highly optimized JIT that the JVM enjoys.

Peak resident memory for the 4M run nearly halved, going from 1.73 GB to 1.04 GB with the B+tree. It's worth noting that the process holds a 4M entry map with its 4M entry set, along with the garbage from building them. So, the numbers here reflect the whole program rather than just the trees themselves. And the JVM run peaked at 4 to 6 GB, but that's mostly an artifact of how the JVM collects garbage with its default settings, so we shouldn't read too much into that.

You might have noticed that the scrambled builds slow down sharply somewhere between 1M and 2M entries. The JVM also shows the same jump with its sort going from 16 to 93 ms. In both cases, the cause is that the working set ends up falling out of cache, making lookup more expensive.

java.util.TreeMap

As I mentioned earlier, Jolt's TreeMap and TreeSet shims are built on the sorted map. These were implemented using a naive approach where they went through it one generic operation at a time. Each put looked up the key and then inserted it, having to walk the tree twice, while navigation methods like floorKey built a subseq and took its first element.

Now, all of these operations have been updated to use the tree directly, meaning that a put or remove is one walk, while operations like floorKey are a single seek. The size of a bounded view can now be computed by adding up whole leaves and only scanning the two partial leaves at the edges. Times are for 20,000 operations.

methodmainB+treeJVM
put (fresh map)34.9 ms7.5 ms2.0 ms
get14.5 ms3.7 ms1.9 ms
floorKey36.4 ms4.4 ms1.7 ms
firstKey/lastKey21.5 ms1.8 ms0.4 ms
remove then put87.2 ms13.8 ms3.7 ms
iterate entries14.8 ms3.8 ms5.8 ms
TreeSet add48.7 ms7.9 ms1.8 ms
headMap size (200 calls)189.8 ms2.7 ms9.3 ms

That's 4 to 70 times faster than the original version, with headMap size beating the JVM, which needs to walk the view in order to count it. But the writes are still about 4x the JVM, and can't be closed with this design because the Java mutates its nodes in place, while Jolt's TreeMap is a mutable wrapper around a persistent tree. So, there's no way around each put having to copy about five nodes.

What behaves differently

Iteration order, which key is kept on a duplicate, which value wins, the argument order passed to custom comparators, and returning the identical collection from a no-op assoc all work as they did before. But there is one thing that's different from the JVM, which stems from the layout of the trees. Building a 1,024 entry map from ascending keys now calls the comparator 1,023 times while the JVM's red-black tree calls it 12,301 times. So, code that counts comparator calls will see different numbers on Jolt.

Takeaways

What this exercise shows is the importance of the memory layout used by the backing data structure. All the operations do the same logical work as before, but they now have to touch about a fifth as many nodes with the data inside each node being contiguous.

Switching to use a B+tree was not a free win, though, since it required a separate batch build path to make the switch efficient for code that builds lots of medium-sized maps, which adds some complexity to the implementation. If you're making a similar kind of optimization, always be sure to measure the middle sizes along with the extremes.

The text above was extracted automatically from the source page and may miss images, tables or code blocks. The original is authoritative.

Published by Lobsters
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗