· JavaScript
Jolt updates sorted collections to B+tree, dropping peak memory by 40%
For a map containing 4 million entries, the new B+tree structure results in a tree that is only 5 levels deep, a significant reduction from the 22 levels required by the previous red-black tree…
For a map containing 4 million entries, the new B+tree structure results in a tree that is only 5 levels deep, a significant reduction from the 22 levels required by the previous red-black tree implementation.
Previously, Jolt's sorted-map and sorted-set utilized a direct adaptation of Clojure's PersistentTreeMap, which relies on a persistent red-black tree. While this structure provided a dependable foundation for these data types, red-black trees inherently necessitate that each entry occupies its own small node. This means that every step taken during a search involves following a pointer to a distinct location in memory. This led to the exploration of alternative data structures capable of achieving the same functionality with less overhead. It turned out that replacing the red-black tree with a B+tree was indeed feasible.
The update to Jolt's sorted collections, alongside the shims for `java.util.TreeMap` and `TreeSet`, now incorporates a persistent B+tree. This change achieved a 40% decrease in peak memory usage and made most operations faster across all data sizes, as the subsequent benchmarks will illustrate. In the old system, every red-black node within Jolt was structured as a five-slot Scheme vector, carrying the color, the key, the value, and its two children. This setup resulted in 48 bytes of metadata per entry, in addition to the space required for the key and value themselves. Given that a map with 4 million entries demands a tree approximately 22 levels deep, a lookup could potentially involve traversing about 22 nodes scattered across the heap. Furthermore, once the tree exceeds the CPU cache capacity, each of these node visits is likely to result in a cache miss.
Writes presented a comparable challenge. Because a persistent tree cannot modify a node in place, performing an `assoc` requires copying every node along the path from the root to the modification, which translates to 22 small allocations followed by rebalancing at that scale. The primary benefit of employing a B+tree lies in its ability to store data within leaves containing up to 16 entries, while branches are managed through inner nodes supporting up to 32 children, with each node being a singular Scheme vector. In this configuration, a leaf is represented as `#(<t k0 v0 k1 v1 ...>)`, placing keys and values adjacent to one another in a continuous memory block. An inner node also stores the largest key below it immediately next to each child. Consequently, the same 4 million-entry tree shrinks to just 5 levels. Moreover, a search within any given node only needs to scan adjacent slots that are already resident in the cache. Although writes still incur the cost of copying the path from the root, this work is now reduced by a quarter, and each copied element is done as a block.
Memory consumption improved markedly, as a full leaf accommodates 16 entries within 34 machine words, requiring only 17 bytes per entry compared to the 48 bytes demanded by the red-black tree. Nodes can also contract to half their capacity before merging, making 34 bytes per entry the highest possible cost in this new design. To keep the common case as close to full capacity as possible, a technique involves initiating a new node when an append operation moves past either end of the tree, rather than splitting a full node into two half-empty ones. This strategy is particularly effective when building data from keys in ascending order, as it packs every node efficiently. Similarly, deletions maintain balance by borrowing entries from a neighbor or merging with it, thereby avoiding the need for rotations.
Naturally, B+trees possess their own limitations. While they excel with large collections, constructing small ones—those comprising only tens to hundreds of entries—by inserting one item at a time proved to be about 15% slower than the red-black tree. This difference stems from the fundamental structure of each data type. When a map reaches 17 entries, it necessitates a root with two leaves, and every insertion demands copying the entire path. Therefore, at smaller sizes, the B+tree must move more bytes during an insertion than the red-black tree, representing a clear trade-off.
Fortunately, this issue can be mitigated by altering how collections are constructed. It is now possible to first gather all inputs for the `into`, `sorted-map`, and `sorted-set` constructors, as well as multi-argument `conj`/`assoc`, to verify if they are already sorted, thereby bypassing the sorting step if they are. Furthermore, duplicate keys can be handled by retaining the first key alongside the last value, which facilitates bulk loading into the leaves. These batches can subsequently be merged with an existing collection. For smaller sources containing eight or fewer entries being added to an empty collection, the system continues to utilize the standard `conj` operation because the overhead associated with buffering would outweigh any potential savings.
With these adjustments in place, the worst-case scenario now involves a 4-entry map operating at 1.05x performance, which is functionally equivalent to the red-black tree. Having discussed the mechanics of B+trees and their advantages over red-black trees in this context, the focus now shifts to concrete benchmark figures comparing the two methods. These measurements were conducted using optimized binaries across multiple runs on an M1 Max equipped with 64 GB of memory. The JVM comparisons utilized Clojure 1.12.6 running on OpenJDK 20. A ratio below 1.0 indicates that the B+tree is performing faster. The timings reflect the entire process over the collection, encompassing its construction, performing a lookup for every key, deleting every key, and replacing every value. To prevent a degenerate sequential case, the keys were also randomized.
The results clearly show that lookups are faster at every scale, by margins ranging from 23% to 33%. Builds and writes remain consistent below the 64-entry threshold. Notably, even a map with only 4 entries is processed as a single leaf searched in place, meaning it does not incur the overhead of the more complex machinery. The `reduce-kv` result is particularly noteworthy, as it reflects an improvement in the new layout. The original red-black tree code generated a map entry for every pair encountered during the generic sequence traversal. By walking the leaves and passing each key/value pair directly to the function, the need to allocate memory for every slot was eliminated. Since the B+tree allows seeking directly to a key to begin reading from that leaf—instead of reconstructing a stack of nodes from the root for every call—repeatedly fetching the first element of a subsequence also becomes quicker.
From this point onward, the impact of cache performance becomes the dominant factor. While performance appeared strong for collections containing thousands of elements, it was crucial to verify behavior with collections reaching millions of entries to ensure no regressions occurred at that massive scale. The subsequent benchmark involves building both a sorted map and a sorted set from scrambled keys, followed by running a mixed set of operations on them. Encouragingly, every operation at this large scale is faster than the prior version. Furthermore, Jolt now surpasses the JVM in building sets, traversing, reducing, and executing range queries, although the two systems are roughly comparable in performance for `contains` and map construction. Finally, point lookups and deletions remain about 1.5 times slower than the JVM, which leverages a red-black tree backed PersistentTreeMap, benefiting from the highly optimized JIT compiler within the JVM.
The peak resident memory for the 4M run nearly halved, dropping from 1.73 GB to 1.04 GB when using the B+tree. It is important to note that these figures account for the entire program state, including the 4M entry map and its corresponding 4M entry set, plus the memory consumed during the build process, meaning they reflect the whole application rather than just the trees themselves. The JVM run peaked between 4 and 6 GB, but this is largely attributed to how the JVM manages garbage collection with its default settings, so this figure should not be interpreted too heavily.
You may have observed a sharp slowdown in the scrambled builds somewhere between 1 million and 2 million entries for both systems. The JVM exhibits the same jump in its sort time, moving from 16 to 93 ms. In both instances, the cause is the working set falling outside of the cache, which increases the cost of lookups. As previously mentioned, Jolt's TreeMap and TreeSet shims are built upon the sorted map. Initially, these were implemented using a straightforward method where they processed one generic operation at a time; each `put` would look up the key and then insert it, requiring two traversals of the tree, while navigation methods like `floorKey` created a subsequence and extracted its first element. Now, all these functions have been updated to interact directly with the tree, resulting in a `put` or `remove` requiring only one traversal, and operations like `floorKey` requiring a single seek.
The size of a bounded view can now be calculated by summing up entire leaves and only scanning the two partial leaves located at the boundaries. Over 20,000 operations, this is 4 to 70 times faster than the original version, and the `headMap` size calculation surpasses the JVM, which must traverse the view sequentially to count it. However, write operations are still about four times slower than the JVM, and this cannot be resolved with the current design because Java modifies its nodes in place, whereas Jolt's TreeMap functions as a mutable wrapper around a persistent tree. Consequently, every `put` must still involve copying approximately five nodes. The behavior regarding iteration order, which key is retained upon duplication, which value prevails, the sequence of arguments passed to custom comparators, and returning the exact same collection
Why it matters
For developers working with data structures, this switch to a B+tree offers significant performance and memory gains for large collections. This tooling update directly impacts how efficiently developers can manage sorted data within Jolt.

