NewsCrawler.org

Shlemiel the Painter Is Back: How Zig's libc Rewrite Made SQLite Slower

An author's chess analysis service — a Rust backend backed by SQLite that hands analysis tasks to runners processing hundreds of chess games — ran into trouble when inserting about 40,000 JSON records took minutes and completely saturated one core, although storing the data should take sub-milliseconds. The culprit was the "Shlemiel the Painter" trap[1] from Joel Spolsky's 2001 piece Back to Basics: a seemingly simple choice that leads to quadratic runtime, like a street line painter who never moves his paint can and spends ever more time walking back to it.

The service is written in Rust, but SQLite is a C project, so the author compiles it with zig cc[2] via cargo-zigbuild, producing Mac ARM64 and Linux ARM64 / x86-64 binaries from one build script on a Mac. Zig's libzigc re-implements the standard library, replacing the musl[3] C dependencies with pure Zig piece by piece. In the rewrites of strspn[4], strcspn, strpbrk and strstr, the first step measures the entire length of the string. Tokenizers work by skipping whitespace, moving to the new string location and repeating, so with these rewrites each step remeasures the whole string endlessly. Tokenizing a 1.2MB file passing JSON to SQLite became approximately 12,000x slower, and the slowdown is quadratic as the file grows. This also explains why the problem appeared on Linux but never on the author's Mac, where zig was not used to compile SQLite.

As a fix, the author pre-pruned whitespace from the JSON, which greatly reduced the tokenizing cost in sqlite3, and then moved the Linux builds over to Linux containers.

Read the original dennisforbes.caDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page