技巧精选

用 Claude 写 SQLite parse_number() 扩展:C 与 Rust 性能对比

parse_number() as a SQLite extension: C vs Rust

精选理由

Simon Willison 让 Claude 用 C 和 Rust 各写了个 SQLite 解析函数,手写的 C 版本最后跑出了 19 ns/行的成绩,过程很值得看。

Simon Willison 让 Claude(Opus 5.5)编写一个 SQLite 扩展函数 parse_number(),将 '$1,234.56'、'12.5%' 这类字符串转为可求和排序的数值。Rust 版本编译产物为 298-321 KB,C 版本只有 14 KB,但 Rust 用 Rusqlite 时每行处理仅需 46 ns,比初始 C 版本的 67 ns 更快。随后 Claude 手写新的 C 解析函数,将 200 万行数据的混合数据每行耗时降到 19 ns,超过 Rust 实现。整个研究过程最终整理成一份放在 GitHub 的研究报告。

原文 · Simon Willison’s Weblog

parse_number() as a SQLite extension: C vs Rust

Research: parse_number() as a SQLite extension: C vs Rust I was out walking the dog when I got curious about how easy/difficult it would be to write a SQLite C extension that adds a parse_number() function for turning strings like -$1,234.56 or '12.5%' into numeric values that could be summed and sorted. I fired up regular Claude chat (Opus 5.5) and prompted : I'm thinking about a SQLite custom function 'parse_number(value)' that strips ',', '$', '£' and '%', handles a leading '-', and returns 'NULL' for anything it can’t parse Explore the difference between building this as a SQLite extension in C v.s. in Rust - I want to compare performance and code complexity and size of the resulting .so (or whatever) file This gave me a solid starting point - the Rust extension was 321 KB (using Rusqlite ) and 298 KB (using sqlite-loadable-rs ), while the C extension was 14 KB. But the Rust extension was faster! Turns out that's because the Rust equivalent of C's strtod is "twice as fast". So I prompted: Try writing your own C function for parsing text into a decimal number that catches up to or beats the Rust implementation And it did: Net cost per row over 2 million rows, lower is better: first C new C rusqlite sqlite-loadable Mixed data 67 ns 19 ns 46 ns 41 ns Integers only 25 ns 16 ns 36 ns 32 ns Decimals only 106 ns 18 ns 55 ns 47 ns Finally, I had it rewrite the prototype as a research report to match the others in simonw/research by prompting this: Clone simonw/research from GitHub and turn your above investigation into a research report as seen in that repository - you can give me a zip file to download that contains your new folder Here's the resulting report . Tags: c , research , sqlite , rust , claude