Lessons from streaming bytes in NuStreamDocs¶
I built NuStreamDocs to generate documentation sites, including this one. It follows one rule: the text stays as bytes from the moment it leaves the disk until it goes back to disk as HTML. This post covers what I learned following that rule, the .NET APIs that make it practical, and what it buys in speed.
The short version: the core of NuStreamDocs builds the 211-page ReactiveUI website in about 11 milliseconds. In its own benchmarks, the parser, the renderer and the syntax highlighter make no allocations at all. An allocation is when a program asks for a new piece of memory to hold something, such as a string or an array. On the same 337 real pages, it built a whole site in about 150 milliseconds, where MkDocs, Zensical and Statiq took between 1.5 and 7.6 seconds. It also turns Markdown into HTML about three times faster than Markdig, a popular and well-optimised .NET Markdown engine, and allocates more than 100 times less memory. Those tools are slower for real reasons, and most of those reasons buy them something NuStreamDocs does not have. The second half of this post looks at why, using their source code.
Why allocations matter¶
Every allocation eventually becomes garbage. The garbage collector is the part of .NET that finds memory nobody uses any more and frees it. It has to stop or slow your program while it works, so the less garbage you make, the less often it runs.
A documentation site has hundreds or thousands of pages. A few small allocations per word or per link add up to millions of objects per build. Most of the lessons below are about not making them in the first place.
Lesson 1: keep the text as bytes¶
Files and web pages store text as UTF-8, where each English letter takes one byte.
A .NET string stores text as UTF-16, where each English letter takes two bytes.
Most Markdown engines in .NET take a string.
That means every file is converted from UTF-8 to UTF-16 on the way in, and the HTML is converted back to UTF-8 on the way out.
Each conversion allocates a new copy the size of the document.
NuStreamDocs reads each file as bytes and never turns it into a string.
Its entry point takes UTF-8 bytes in and writes UTF-8 bytes out:
public static void Render(ReadOnlySpan<byte> markdown, IBufferWriter<byte> writer)
ReadOnlySpan<byte> is a span, a window onto memory that already exists.
Making a span copies nothing and allocates nothing.
IBufferWriter<byte> is a buffer writer, something you can write bytes into without knowing in advance where they end up.
Lessons 2 and 3 come back to both.
Fixed text in the code uses UTF-8 string literals.
Adding u8 after a string tells the C# compiler to store it as UTF-8 bytes when it builds the program, so nothing is converted while the program runs:
if (source.IndexOf("]:"u8) >= 0)
{
// The page may contain reference-style links.
}
The rule is strict enough that string is banned in NuStreamDocs' production code.
Some outside APIs do need a string.
Where text crosses into one of those, a small wrapper type called ApiCompatString marks the spot, so it is easy to find in review.
Lesson 2: read with spans, not substrings¶
A parser reads the Markdown and works out its structure: which lines are headings, which are lists, where each link starts and ends.
Substring allocates a new string every time you call it.
A parser that calls it for every heading, link and word creates thousands of small objects per page.
A slice of a span costs nothing.
text[start..end] gives you a view of the same memory, so the parser can pass pieces of the page around without copying them.
Lesson 3: write into a buffer writer¶
A renderer takes the structure the parser found and writes it out as HTML.
Building HTML with StringBuilder or by joining strings grows and copies a buffer as the page gets longer.
It then copies the result once more to make the final string.
The NuStreamDocs renderer writes HTML straight into the buffer writer. The caller decides where the bytes go. In a site build, the same buffer is reset and reused for every page, so after the first page it never needs to grow again.
Lesson 4: check before you work¶
Most pages do not use most features. Most pages have no tabs to expand, no reference-style links and no citations. So each step first asks one cheap question, and skips all its work when the answer is no:
// Only pages that contain a tab pay for tab expansion.
internal static bool MayNeedExpansion(ReadOnlySpan<byte> source) => source.IndexOf(Tab) >= 0;
The question is cheap because IndexOf on a span of bytes is vectorised.
Vectorised code uses SIMD (single instruction, multiple data), a CPU feature that checks 16, 32 or 64 bytes in one step instead of one byte at a time.
The bibliography step shows how much this matters. A page with no citations passes through it in 225 nanoseconds, which is 225 billionths of a second.
Lesson 5: search with SearchValues¶
Escaping HTML means finding every &, <, > and " and replacing it with a safe code such as &.
Checking each byte against four characters in a loop is slow.
.NET 8 added SearchValues, which works out the fastest way to search for a fixed set of values once, up front.
NuStreamDocs builds the set once and uses it for every page:
private static readonly SearchValues<byte> EscapeBytes = SearchValues.Create("&<>\""u8);
The escaper then jumps from one special byte to the next, and copies everything between them in one block:
var idx = cursor.IndexOfAny(EscapeBytes);
A page with nothing to escape is copied in a single step.
Lesson 6: rent and reuse buffers¶
Some steps need a temporary buffer, for example to hold a page after its tabs have been expanded. Allocating a fresh array for that on every page would undo the rest of the work.
ArrayPool<byte>.Shared is a shared pool of arrays.
You borrow an array with Rent and give it back with Return, so the next caller can use it:
var buffer = ArrayPool<byte>.Shared.Rent(length);
try
{
// Use the buffer.
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
The renderer also keeps one list of parsed blocks per thread, and reuses it for that thread's next page. A thread is one of the workers that render pages side by side. The renderer stops keeping a list once it has grown very large, so one huge page cannot hold on to megabytes of memory for the rest of the build.
Lesson 7: give up the convenient tools in hot paths¶
A hot path is code that runs so often that its speed decides the speed of the whole program. Three convenient tools are banned from NuStreamDocs' production code, because they cost too much there:
- Regular expressions. A regular expression is a pattern language for matching text. Each pattern runs on a general matching engine. A small scanner written for one pattern is faster, and its behaviour is easier to see.
- LINQ. LINQ is .NET's query syntax for collections, such as
pages.Where(p => p.IsDraft). It creates small helper objects on most calls. A plainforloop over an array does not. string. For the reasons in lesson 1.
That sounds harsh. In practice the scanners are short, and each one has tests that pin down exactly what it matches.
Lesson 8: measure, don't guess¶
I could not have found most of these wins by reading code. Every change goes through BenchmarkDotNet, the standard tool for timing .NET code. Allocations are traced with EventPipe, the .NET runtime's built-in recorder, which logs what was allocated and which code asked for it.
The traces show where the memory and time go:
- 81% of all memory allocated across the benchmark suite is
byte[], the UTF-8 buffers the pipeline is designed around. stringis 3.6%, and appears only where text crosses into an outside API.- The busiest functions are the runtime's own vectorised
IndexOfand its memory copy. No single NuStreamDocs method uses more than 1.1% of the CPU time.
That last point is the goal. When the top of the profile is the runtime's SIMD code, the program spends its time searching and copying bytes, which is all a renderer should be doing.
The numbers¶
NuStreamDocs on its own¶
These figures come from the NuStreamDocs benchmark results, measured on an AMD Ryzen 7 5800X with .NET 10. A microsecond (µs) is a millionth of a second, and a millisecond (ms) is a thousandth.
| Workload | Time | Memory allocated |
|---|---|---|
| Parse a 1,000-paragraph page | 160 µs | 0 B |
| Render a 1,000-paragraph page | 138 µs | 0 B |
| Highlight a C# snippet | 76 µs | 0 B |
| Build the 211-page ReactiveUI site, core pipeline | 11.2 ms | 770 KB |
| Build the same site with all common plugins | 87.9 ms | 13.2 MB |
That is about 19,000 pages a second for the core pipeline, and about 2,400 pages a second with navigation, highlighting, search and diagrams turned on. These build times include reading the files and writing the HTML to disk.
NuStreamDocs against MkDocs, Zensical and Statiq¶
These are whole-site generators, so the fair test is a full site build. MkDocs is the Python site generator most documentation sites use. Zensical is a newer Python and Rust generator from the team behind Material for MkDocs. Statiq is a .NET site generator, and it built this site before NuStreamDocs did.
A single build time hides two different costs. The fixed cost is what a tool pays before it renders anything: starting the runtime, loading code and reading settings. The per-page cost is what each extra page adds. To separate them, I built each site twice: once with one page, and once with all 337 ReactiveUI pages. The difference between the two, divided by 336, is the cost of one extra page.
Each build started the tool as a new program, so the time includes start-up, which is what you wait for at the command line. The output folder was deleted before every build. "Clean" means I also cleared the tool's own cache, and "warm cache" means I left it in place. All the tools ran in one session on the same machine, so the rows can be compared with each other.
| Tool | 1 page | 337 pages | Each extra page |
|---|---|---|---|
| NuStreamDocs 1.20.1 | 99 ms | 147 ms | 0.14 ms |
| NuStreamDocs, with extensions, highlighting and contents | 132 ms | 221 ms | 0.27 ms |
| MkDocs 1.6.1 | 113 ms | 2,583 ms | 7.35 ms |
| Zensical 0.0.63, default settings, clean | 332 ms | 7,605 ms | 21.64 ms |
| Zensical, default settings, warm cache | 243 ms | 1,576 ms | 3.97 ms |
| Zensical, MkDocs' extensions, clean | 255 ms | 3,343 ms | 9.19 ms |
| Zensical, MkDocs' extensions, warm cache | 244 ms | 1,464 ms | 3.63 ms |
| Statiq.Web 1.0.0-beta.60 | 2,815 ms | 4,067 ms | 3.73 ms |
Each time is the average of 10 builds after 2 warm-up builds. The standard deviation, a measure of how much the 10 builds varied, was within 6% of the average for every row except Statiq, whose builds varied by up to 15%.
Two things stand out. MkDocs and NuStreamDocs start in about the same time, so the whole gap between them is per-page work. Statiq is the opposite: most of its time is fixed start-up, and its per-page cost is close to Zensical's warm one.
The test has limits. The themes are different, so each tool wrote different HTML around the same content. Zensical turns on about 20 Markdown extensions by default, including Pygments, a Python syntax highlighter. That is why its default rows are slow, and why I added rows with only the extensions MkDocs uses. Statiq wrote 335 pages rather than 337, and MkDocs and Zensical each added a 404 page.
Why the others are slower, and what they get for it¶
I downloaded the source of each tool and profiled the builds to find where the time goes. None of these tools is badly written. Each one made a different trade, and the trade shows up in the numbers.
MkDocs¶
MkDocs converts Markdown with Python-Markdown, a Python library that has been around since 2004. Python-Markdown works in stages. It first runs preprocessors over the lines of text, then splits the text into blocks, then builds a tree of elements in memory. After that it runs inline patterns over the tree, which are regular expressions that find links, emphasis and code. Finally it turns the tree into a string of HTML and runs postprocessors over that string. Each stage walks the whole page again and creates new Python objects and strings.
In a separate run, Python-Markdown alone took about 1.5 seconds for the 337 pages, with the same extensions MkDocs uses. That is a bit over half of MkDocs' build.
Most of the rest is the navigation. MkDocs renders the full site menu into every page, using Jinja2, a Python template engine. Every link in that menu is worked out relative to the current page. In the profile, the menu template ran about 2 million times and the relative-link function about 121,000 times for one build. More pages means a bigger menu on every page, so this part grows faster than the page count.
What MkDocs gets for this is flexibility. Python-Markdown's stages are where its extensions plug in, and there are hundreds of them. The plugin and theme ecosystem around MkDocs and Material for MkDocs is the largest of any documentation tool. A Python developer can change almost anything with a few lines of code. For most sites, a build of a few seconds is a fair price for that.
Zensical¶
Zensical has a core written in Rust, a fast compiled language, and it still uses Python-Markdown for the Markdown itself. For each page, the Rust core calls into Python, which sets up a new Markdown converter with every configured extension and renders the page. So the per-page cost is close to MkDocs' Markdown cost, and its default extensions add more on top.
Zensical's strength is the cache. With a warm cache it rebuilt the site in about 1.5 seconds, faster than MkDocs from scratch. It is designed for the edit-and-preview loop, where you change one page and want to see it straight away. It also turns on a rich feature set by default, so a new site looks finished without any setup. The project is young, and it plans to move more of the work into Rust, so I expect these numbers to change.
Statiq¶
Statiq is a .NET framework for building any kind of static site, not only documentation. Its build is a chain of modules, and each one reads and writes documents through a general pipeline. It renders Markdown with Markdig, and builds a new Markdig pipeline for each document. After rendering, it parses each page's HTML again with AngleSharp, a .NET HTML parser, once to make the excerpt and once to collect headings. That is two full HTML parses per page on top of the Markdown.
Most of Statiq's time, though, is its start-up of about 2.8 seconds. It loads a large set of modules and sets up the engine before it reads a single page.
What Statiq gets is generality. You can build a blog, a documentation site or something else entirely from the same modules, and write new ones in C#. This site used Statiq for years, and it did that job well.
Markdig¶
Markdig is the engine behind Statiq and many other .NET tools, so the comparison in the next section uses it directly.
Markdig parses each page into an abstract syntax tree, a tree of objects where every heading, paragraph and link is its own object.
It then walks the tree and writes HTML through a TextWriter, which works in UTF-16 strings.
Those objects and strings are where its allocations come from.
The tree is also Markdig's greatest strength. Extensions can inspect and change it before anything is written. Each node knows exactly where it came from in the source, which editors and linters need. Markdig follows the CommonMark specification closely and supports a long list of extensions. NuStreamDocs gives up some of that. It does not keep a full tree, so a tool that needs to edit the structure of a page is easier to write on Markdig.
What NuStreamDocs gives up¶
The speed is not free. NuStreamDocs supports a fixed set of features, written by me. It has no ecosystem of outside plugins yet, and adding a feature means writing a byte scanner rather than a regular expression. It is also new, so it has had far fewer users find its edge cases. If you need a particular MkDocs plugin, or a theme from the MkDocs world, MkDocs is still the better choice today.
Rendering only: NuStreamDocs against Markdig¶
To see how the byte-first approach compares, I rendered the same documents with NuStreamDocs 1.20.1 and with Markdig 1.6.0. The test set is the 337 Markdown pages of the ReactiveUI website, 4.65 MB in all. Each run renders every page once.
I gave Markdig its best case.
Its pages were already loaded as strings, so the time to convert them from UTF-8 is not counted.
I measured it two ways: returning a new string per page, and writing into one reused StringWriter.
Both engines ran with no extensions, and both skipped each page's front matter, the block of settings at the top of the file.
| Engine | .NET 10 | .NET 11 | Memory allocated |
|---|---|---|---|
| NuStreamDocs, bytes into a reused buffer | 5.89 ms | 5.80 ms | 256 KB |
Markdig, string into a reused StringWriter | 17.59 ms | 17.20 ms | 26.9 MB |
| Markdig, string into a new string | 20.22 ms | 19.75 ms | 37.7 MB |
NuStreamDocs rendered the pages about three times faster. It allocated 105 times less memory than Markdig's fastest method, and 147 times less than its usual one.
Memory tells the bigger story. The garbage collector sorts objects into generations by age. Generation 0 holds new objects and is cheap to clean. Generation 2 holds objects that survived earlier passes, and cleaning it is the most expensive pass of all. Markdig's usual method caused generation 2 collections during the run. NuStreamDocs caused none, and fewer than one cheap generation 0 collection per run. In a real build, that difference grows with every page.
Each time is the average of 15 runs after 5 warm-up runs, and every result sat well outside its margin of error. I ran it with BenchmarkDotNet 0.16 on an Intel Core Ultra 5 250K Plus under Fedora Linux, pinned to five performance cores.
Two limits are worth knowing. First, the two engines do not produce identical HTML, so this compares two engines doing the same job, not the same output byte for byte. Second, this is one machine and one set of documents. Your pages and your hardware will give different numbers, but the gap in memory comes from the design, so I expect it to hold.
What I would tell someone starting out¶
- Decide early what form your data lives in, and keep it in that form. Every conversion costs a copy.
- Treat every allocation in a loop as a bug until a measurement says otherwise.
- Ask the cheap question first. Most of the work you skip is the fastest work there is.
- Lean on the runtime.
IndexOf,SearchValuesandArrayPoolare faster than anything I would write by hand. - Measure every change, and keep only what the numbers prove.
NuStreamDocs is open source on GitHub, and this site is built with it.