Tried to make a fast Markdown library for streaming LLM text

So i was working on my little SwiftUI app, and I needed some lightweight library for Markdown which is also fast for streaming.

Looked for different options like MarkdownUI and Textual, etc. MarkdownUI looked like a pretty good option, as it has really nice flexibility, where you can use custom SwiftUI views for different parts. i guess that flexibility was one of the main causes of it being slower than what i needed. And as i understand, its because to measure the height of the view inside text it has to render the whole view first. In my bench, MarkdownUI missed 170 frames on a mixed answer.

So, the key optimizations i tried:

  • Since the output is streamed, so the content grows only at the end, and markdown blocks before the last one can not change
  • If so, we can skip unchanged blocks, and re-parse only last one which is updated
  • And the same is for block conversion. Instead of converting each block to attributed string, we convert only the top-level blocks whose markdown content changed
  • And avoid using SwiftUI views for things like code blocks, tables, etc. So it's implemented as AppKit views, with a faster way to calculate their height. E.g. for a code block, its height is literally: number of lines * line height + paddings + etc.

Its macos only for now, since i use AppKit views for the code blocks and tables, etc.

The benchmark is going to be a stream of a 32kb response, imitating the response from LLM, with about 120 bytes every 50ms. Going to measure missed frames on 60fps, cpu and memory utilization, and a time to load full “answer”. So I ran it and compared my library with others, like MarkdownUI, Textual and also microsoft’s SwiftStreamingMarkdown. And going to keep the plain text view as a baseline.


Mixed answer, median of 5 runs on an M2

Missed frames out of ~820 while a 32 KB answer streams (median of 5, M2 8 GB):

Library Mixed Prose Code Table Open full (mixed)
Mine (Sumi) 91 29 44 192 40ms
SwiftStreamingMarkdown 3 7 10 411 672ms
MarkdownUI 170 167 133 786 200ms
Textual 538 402 252 814 617ms
Plain NSTextView (no MD) 2 2 1 3 19ms

So microsoft's SwiftStreamingMarkdown is noticeably "smoother", it had the least missed frames. Appears its because it parses the whole text again on each update, but off the main thread, what keeps the UI smooth, but costs more CPU (52% on mixed, up to 158% on code), and it takes 0.3–1.4s to open a full answer. It also misses more frames than mine on tables (411 vs 192).

I'm new to Swift, and have learned a lot along this side quest.
For curious, the library is open-source with benchmark here:

2 Likes