Skip to content
Engineering

Architecture

B-trees keep our text editor fast at a million words

In this post

In Milieu’s editor, a keystroke takes about 5 ms in Chrome, even in a note containing a million words. Our first version took most of a second in a note a fifth that size.

The old editor read the whole note on every keystroke. The new one reads only the part you’re typing in. Three data structures make that work: a persistent B-tree that copies for free, an order-maintenance list that finds any character by its id, and paragraphs that keep their identity, so the page redraws only the paragraph you changed.

Try it below, with 100,000 words or a million. Type anywhere to see how long each keystroke takes. Under the note is the editor’s own tree, along the path from its top node down to your caret. Click any part of the tree to jump there.

A long note Interactive

This is Milieu’s editor, as it is in the app. Click anywhere in the note and type, and see how long each keystroke takes. Under it is the editor’s own tree, along the way down to your caret.

100,000 words will be drawn here as you reach it.

Each keystroke’s time will show here.

Counterintuitively, typing quickly makes each keystroke faster, and typing slowly makes it slower: in Chrome, about 2 ms when you type quickly, and 5 to 10 ms after a pause. We think the processor might slow down or its caches go cold between keystrokes, but to be honest we’re really not sure why it varies as much as it does.

Where a keystroke’s time went

A keystroke does the same few things however long the note is. In our first version, each of those steps went through the whole note:

A keystroke has to…First version went throughNow goes through
1Find where you’re typingEvery characterOne path down a tree
2Copy the text, for undoEvery characterOne pointer
3Make the editEvery character after itOne path down a tree
4Work out what changedEvery paragraphThe paragraph you typed in
5Draw itEvery paragraphOne chunk of about 32
6Find it on the pageEvery paragraph on the pageOne lookup by key

None of these steps is slow on its own, and in a short note all of them together took about a millisecond. But each step took longer as the note grew, so a note ten times as long meant about ten times the wait. The rest of this post is how each step stopped growing.

A tree that counts

A note is kept as pieces: runs of characters typed one after another by one person, with the same formatting. Most typing carries on from the end of a piece and makes it longer, so a sentence you type is usually one piece.

The pieces sit in the bottom nodes of a B-tree, which are called its leaves. A B-tree is a tree whose nodes each hold a handful of children, up to 32 in Milieu’s, so even a huge note is only a few levels deep: a million words is four. The trick is that every node knows how many characters are under it.

That turns finding a position into a short walk. To find the 500,000th character, look at the top node’s children and add up their counts until you reach the child that holds character 500,000. Then do the same inside that child, and so on down to a leaf. Each level is at most 31 additions, and nothing reads any text.

The demo below does the same walk in a short note. To make the whole tree fit on screen, its nodes hold at most three children instead of 32. Click any character to watch the walk down to it:

Finding a position Interactive

Click a character to watch the walk down to it.

  1. At the top: pass 21 characters, 21 so far.
  2. Down a level, it’s in the first child.
  3. In the leaf, it’s in the first piece.
  4. Then 11 into “ about the venue”: “v” is at 21 + 11 = 32, without counting 32 characters.

Each node counts more than characters. It also counts paragraph breaks, words, bytes and graphemes. A grapheme is a character as people see it, so an emoji, or a letter with its accent, counts as a single grapheme. Because every node keeps these counts, the note’s word count is just the word count of its top node.

Words need one extra detail. A word can run from one node into the next, so each node also says whether its text starts or ends in the middle of a word. When a parent finds a word split between two of its children, it counts that word once.

In code, a node looks like this (simplified):

class Branch {
	readonly children: readonly Node[];
	readonly length: number; // characters under it
	readonly breaks: number; // paragraph breaks
	readonly words: Words; // and whether it starts or ends mid-word
	readonly bytes: Bytes; // in UTF-8
}

Never change a node

No node in the tree changes once it’s made. Instead, a keystroke makes a new leaf with the new letter in it, then a new parent to hold that leaf, and so on up to a new top node. Each new node works out its counts again from its children. Every other node is shared between the tree before the keystroke and the tree after it. Click a character to type a letter after it:

A keystroke makes a new path Interactive

Each leaf holds up to three pieces, shown by its dots. Type where a leaf has room, then where one is full, or click any character to type after it.

Every node is kept as it is once it’s made.

So a keystroke makes about one node per level, which is four in a million words, and keeping every count right costs at most a hundred or so additions.

Never changing a node also means the old tree is still there, whole, for as long as anything refers to it. Copying a text is just copying a reference to its top node. That’s what makes undo free, and it’s why an edit that fails part-way leaves the text exactly as it was.

Finding a character that moves

Finding a character by its position isn’t enough, because several people can type in a note at once. As Typing together without CRDTs explains, an edit says where it goes by naming a character’s id instead. Ids aren’t in the order the text reads, so the counts in the tree can’t find a character by its id.

So each piece also has a place, a number from an order-maintenance list, and the tree keeps pieces in the order of their places. Finding a character by id is then a lookup from its id to its place, followed by a walk down the tree to that place.

Text typed between two pieces gets the number halfway between their places. When there’s no number left between them, the places nearby are spread out to make room, without changing their order. The demo below runs the editor’s own list, but with places only up to 128, so you can run out of room:

Places between places Interactive

Each word is a run of text, and the number beside it is its place. Click a word to put new text straight after it, and click the same one a few times to use up the numbers in between.

Six places, 16 apart, with room for more between each.

Every copy of a text, old or new, shares one list. That works because spreading places out changes their numbers but never their order. The list is a simplified form of the algorithm in Bender and others’ Two Simplified Algorithms for Maintaining Order in a List.

The page is a tree too

The tree answers questions about the text in a few steps. But the page has to change too, and a million words make about 90,000 paragraphs on the page.

Each paragraph is drawn from a shape: what the paragraph says and how it’s styled, but not where it starts in the text, because that changes with every edit above it. A keystroke makes new nodes only on its path, so it makes only one new shape, and every other paragraph’s shape stays the same object as before. The editor redraws just the paragraph whose shape is new.

Svelte, which draws the page, still compares every paragraph it’s given with the paragraph it drew last time. So the editor hands Svelte the paragraphs in chunks of about 32, each in an element of its own, and Svelte skips every chunk that’s the same object as before.

Where a chunk ends depends on the paragraphs themselves. Each paragraph has a key, and a chunk ends at any paragraph whose key happens to hash to a multiple of 32. Adding a paragraph then changes only the chunk it’s added to. If chunks were cut every 32 paragraphs instead, adding a paragraph would shift every chunk after it along by one paragraph.

In the demo below, chunks hold about six paragraphs, so that a short note has several. Add a paragraph near the top, then switch to cutting every six paragraphs and add one again:

Where chunks end Interactive

Each square is a paragraph, and each box a chunk the page draws on its own. Add a paragraph near the top, then switch to cutting every six paragraphs and do it again.

42 paragraphs in 9 chunks.

A million words still make nearly 3,000 chunks, and browsers don’t like an element with thousands of children, because much of what they do goes through the children one by one. So the chunks are grouped into sections of about 32 in the same way. That took a keystroke in a million words from 79 ms to 2.2 ms in WebKit.

Drawing all 90,000 paragraphs takes 3.3 s in Chromium and 7.9 s in Firefox. After that, thanks to content-visibility: auto, the browser lays out only the chunks near the screen. Until a chunk comes into view, it takes up the room it took the last time it was laid out, or, before that, a flat guess at the height of about 32 short paragraphs. We don’t try to guess how the text wraps, because working that out is the layout we’re trying to skip.

What surprised us

One CSS property cost more than our editor. The box around these demos was a CSS size container, so the demos could adapt to their width. With the editor inside that box, Chromium recalculated style for the whole note on every keystroke: 7.8 ms at a million characters, where without the size container the same work took no time at all. The demo at the top now goes without it.

Measuring the editor made the browser lay out the note twice. The editor read its own width as it drew, so that it could place other people’s cursors and checklist boxes beside the text again whenever the width changed. Reading the width made the browser lay out every paragraph before the editor had finished drawing them, and then again after. Having the browser report the width once layout was done saved 200 ms in Chromium and 400 ms in WebKit when opening a million characters.

Firefox pays for the whole editable area. Changing the text of one paragraph in a 90,000-paragraph editable element takes Firefox 14 ms on its own, before our code does anything, and no time at all when the element isn’t editable. That’s most of what a keystroke costs in Firefox.

The slow part is the browser now

In our measurements of a million-word note, our own code is now the smaller part of a keystroke. Most of the time goes on the browser keeping a page of 90,000 paragraphs up to date: laying it out, putting the cursor back, and in Firefox, looking after a very large editable element.