Sub topic 15
Wide-node trees: why B-trees beat binary trees in memory
This chapter assumes you know the cache line model from earlier chapters: memory moves in 64-byte blocks, and a pointer chase can cost a full miss. You should also be comfortable with binary search trees, big-O notation, and C structs.
The problem with binary nodes
A binary search tree does about log2(n) comparisons per lookup. For a million keys, that is about 20 steps. Big-O says this is optimal. The cache says otherwise.
A typical node holds a key and two child pointers. On a 64-bit machine that is 24 bytes, or 32 with a value. The allocator places nodes wherever it finds room, so each step down the tree usually lands on a different cache line. Each step also depends on the previous load, because you cannot know the next address until the current node arrives. The hardware cannot prefetch past that dependency.
So a lookup in a million-key binary tree costs up to 20 serial misses, each using a 64-byte line to deliver about 8 useful bytes. Only the top levels stay in cache, because they are touched by every lookup.
The wide-node idea
A wide-node tree packs many keys into one node and gives it many children. The B-tree is the classic design. A node with up to M children stores up to M - 1 sorted keys. A lookup does two things per node:
- Search the keys inside the node, usually with a linear scan or a small binary search.
- Follow one child pointer to the next node.
The tree height drops from log2(n) to log_M(n). With M = 16, a million keys need about 5 levels instead of 20.
The comparison count stays about the same, since searching 16 keys costs about 4 comparisons. What shrinks is the number of cache lines you must fetch, because the keys inside a node are adjacent in memory.
Sizing a node to the cache line
The node size is the tuning knob. A good starting point is to make a node span one or a few cache lines.
Take 32-bit integer keys and 32-bit child indexes. A 64-byte line holds 16 four-byte values. You could store 7 keys and 8 child indexes plus a count. Larger nodes hold more keys per visit but cost more bytes to scan.
Several details affect the result:
- Alignment. A node that straddles two lines costs two misses. Allocate nodes on 64-byte boundaries.
- Child links. Pointers are 8 bytes, so they eat space. Using 32-bit indexes into a node pool, or storing children contiguously, fits more keys per line.
- Adjacent-line prefetch. Many CPUs fetch pairs of lines together, so a node of 128 bytes is often almost as cheap as one of 64.
- Disk-style sizes. Database B-trees use 4 KB or 8 KB nodes to match disk pages. In-memory trees work better with much smaller nodes, because the unit you are matching is the cache line, not the page.
A cache-aligned node in C
This sketch shows a read-only node layout for integer keys and a lookup that scans the node linearly. It is a search structure only; building it is covered by the exercise at the end.
#include <stdint.h>
#include <stdio.h>
#include <stdalign.h>
#define KEYS 7
/* Exactly one 64-byte cache line:
4 (count) + 7*4 (keys) + 8*4 (children) = 64 bytes. */
typedef struct {
uint32_t count;
int32_t keys[KEYS];
uint32_t child[KEYS + 1]; /* indexes into the node array; 0 means none */
} Node;
_Static_assert(sizeof(Node) == 64, "node must fill one cache line");
/* Returns 1 if key is present. nodes[1] is the root; index 0 is unused. */
int contains(const Node *nodes, int32_t key) {
uint32_t cur = 1;
while (cur != 0) {
const Node *n = &nodes[cur];
uint32_t i = 0;
while (i < n->count && key > n->keys[i])
i++;
if (i < n->count && key == n->keys[i])
return 1;
cur = n->child[i];
}
return 0;
}
int main(void) {
static alignas(64) Node nodes[4] = {0};
/* Root holds 20 and 40; three leaves hold the rest. */
nodes[1] = (Node){ .count = 2, .keys = {20, 40}, .child = {2, 3, 0 + 0} };
nodes[1].child[2] = 0;
nodes[1].child[0] = 2;
nodes[1].child[1] = 3;
nodes[1].child[2] = 0;
nodes[2] = (Node){ .count = 2, .keys = {5, 10} };
nodes[3] = (Node){ .count = 2, .keys = {25, 30} };
printf("%d %d %d\n", contains(nodes, 10), contains(nodes, 30), contains(nodes, 99));
return 0;
}Running it prints 1 1 0. Each visited node costs one aligned line fetch, and the scan inside it touches only data already loaded.
Why the scan inside a node is cheap
Scanning 7 keys linearly looks wasteful next to a binary search. In practice it is often faster:
- The keys are in one cache line, so every comparison hits L1.
- A linear scan has predictable branches and an easy access pattern, and compilers can vectorize it.
- A binary search inside a small node has unpredictable branches. A mispredicted branch costs roughly 15 to 20 cycles, which is more than the extra comparisons.
For nodes beyond a few cache lines, a binary search within the node starts to win. Measure to find the crossover for your key type.
Trade-offs and edge cases
Wide nodes are not free.
| Aspect | Binary tree | Wide-node tree |
|---|---|---|
| Cache lines per lookup | About log2(n) | About log_M(n) |
| Insert cost | One node written | Shift keys inside a node, occasional split |
| Memory overhead | Pointers per key | Partly empty nodes, often 50 to 100% full |
| Code complexity | Low | Splits, merges, and rebalancing |
| Pointer stability | Stable | Keys move between slots |
Keep these edge cases in mind:
- Splits. When a node fills up, it splits in two, and the median key moves up. This keeps all leaves at the same depth, which is why lookup cost stays predictable.
- Fill factor. After random inserts, nodes are about 70% full on average. Space and cache use are slightly worse than the ideal.
- Iterators. Insertions shift keys, so references to keys and iterators may be invalidated. This differs from
std::map, which guarantees stable references. - Small data. For a few dozen keys, a sorted array with binary search beats any tree.
- Ordered scans. B+ trees keep all values in leaves and link the leaves together. A range scan then reads sequential lines, which the prefetcher handles well.
Measuring the difference
The effect is easy to miss on small inputs, because a few thousand keys fit in L2. Test with data larger than your last-level cache, and use random lookups so the prefetcher cannot help the binary tree. Compare cache misses with perf stat -e cache-misses alongside wall-clock time. Expect the gap to grow with tree size.
Exercise
A tree stores 1,000,000 keys. A binary tree has height about 20. A B-tree has 15 keys and 16 children per node. Roughly how many levels does the B-tree need, and why does a lookup cost fewer cache misses even though it compares a similar number of keys?
Show answer
The height is about log base 16 of 1,000,000, which is about 5 levels. Each level costs about one cache line fetch, because the 15 keys sit next to each other in one node. The binary tree needs about 20 dependent fetches, each landing on a different line. The B-tree does about the same number of comparisons (around 4 per node over 5 nodes), but those comparisons hit data already loaded, so only about 5 misses occur instead of up to 20.
Exercise
In the C example, the node holds 7 keys and 8 child indexes. Suppose you switch the child links to 8-byte pointers. How many keys fit in a 64-byte node if you keep a 4-byte count and 4-byte keys?
Show answer
Let k be the number of keys. A node needs 4 + 4k + 8(k + 1) bytes, which is 12k + 12. For this to be at most 64, k is at most 4 (12*4 + 12 = 60). So only 4 keys fit, compared with 7 using 32-bit indexes. This is why compact child indexes help.