Three Reads, and Two of Them Were Already in Memory
Last timeSorted Means Searchable
Put the keys in sorted pages and build pages of signposts above them. The depth is tiny because a page holds hundreds of keys, and the top of it never leaves memory.
The previous lesson ended with the design: leave the rows alone and build a separate structure holding the keys in order. This lesson builds it, and the whole of it follows from one observation about page sizes.
A page of pointers
The sorted file halved the search on every read because a page told you one thing: is the target above or below this page. That is a waste of a page. An eight kilobyte page can hold far more than one signpost.
Fill a page with key-and-pointer pairs instead. Each pair says: everything from this key onwards lives under this page. Now one read does not eliminate half the remaining file, it eliminates all but a few hundredth of it.
| step | what sits in each pair | bytes a pair, key plus an eight-byte pointer | children one page points at | keys three levels then cover | what happened |
|---|---|---|---|---|---|
| 1 | an eight-byte integer key | 8 + 8 = 16 bytes | 8,000 / 16 = 500 | 500 x 500 x 500 = 125 million | The arithmetic on its own, before any implementation has had its say. One read eliminates all but a five-hundredth of what is left, where the sorted file of the last lesson eliminated half. |
| 2 | the same key, once the page keeps its own bookkeeping and the slack it leaves for later insertions | a little more than 16 bytes | a few hundred, call it 300 | 300 x 300 x 300 = 27 million | Three hundred is the number to carry around. The slack is deliberate rather than waste: a page with room left in it can take an insertion without splitting. |
| 3 | a hundred-byte text key | 100 + 8 = 108 bytes | 8,000 / 108 = about 74 | 74 x 74 x 74 = about 405,000 | The same structure, the same page size, a quarter of a million times less reach for three levels, bought entirely by the width of the key. |
Depth from branching
With a branching factor of three hundred, count what each level can hold. The bottom level holds the keys themselves, three hundred to a page. One level up, each page points at three hundred bottom pages, so it covers ninety thousand keys. One level above that covers twenty-seven million.
The lesson stops here
3 more paragraphs to go
You have read the opening. The rest of the argument, the problems that check whether it landed, and the lines worth keeping at the end all come with a plan.
The first lesson of every course in the library reads the whole way through, free, so you can see exactly what the rest of them are.
See the planThe contentsThis is the reading half
Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.
The contents