Something went wrong. Try again.
The Unicode Collation Algorithm (UTS #10) and CLDR locale tailorings in Zig: sort text the way people expect rather than by code point.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the four steps cost, per corpus.//!//! Here because a performance change needs a number in front of it. Section//! 9.5 of UTS #10 suggests skipping step 1 for text that is already in FCD//! form, and the question that decides whether to do it is what step 1 is//! actually costing -- which depends entirely on the text. A string of ASCII//! decomposes to itself; a Hangul syllable decomposes arithmetically to three//! jamo; Vietnamese in NFC decomposes every letter and then reorders the//! marks.//!//! Each corpus is timed twice: once for the whole of `writeSortKeyUtf8`, and//! once for step 1 alone, so that the share is visible. The numbers are//! nanoseconds on one machine and are only ever worth reading as a//! *comparison* -- before against after, or corpus against corpus.//!//! `latin-nfc` and `latin-nfd` are the same twenty words in the two//! normalization forms, which is the pair that says what the rest of section//! 9.5 could be worth: FCD input would be handled the way NFD input already//! is, so the difference between those two rows is the ceiling.//!//! An earlier version also timed a bare UTF-8 decode as a "floor" and//! reported step 1 above it as headroom. That column is gone: the loop//! measured *slower* than step 1 itself on ASCII, which makes it no kind of//! bound, and a benchmark that prints a number nobody can act on is worse//! than one that prints fewer.//!//! Each corpus is also weighed once with the root collation and once with a//! tailoring, because a tailored table is a second lookup in step 2 and the//! share therefore differs.//!//! Usage: `zig build bench -- [iterations]`.
const std = @import("std");const collate = @import("collate");
const Corpus = struct { name: []const u8, why: []const u8, strings: []const []const u8,};
const corpora = [_]Corpus{ .{ .name = "ascii", .why = "nothing decomposes and nothing reorders", .strings = &.{ "Smith", "Jones", "Williams", "Brown", "Taylor", "Davies", "Wilson", "Evans", "Thomas", "Johnson", "Roberts", "Walker", "Wright", "Robinson", "Thompson", "White", "Hughes", "Edwards", "Green", "Hall", }, }, .{ .name = "latin-nfc", .why = "every accented letter decomposes, and most text arrives like this", .strings = &.{ "Märtens", "Möller", "Mueller", "Ærø", "Åkerman", "Čapek", "Dvořák", "Grün", "Hüttner", "Jäger", "Køge", "Lübeck", "Nørgård", "Öland", "Piñeiro", "Quiñones", "Ruiz", "Sørensen", "Tørring", "Zürich", }, }, .{ .name = "latin-nfd", .why = "the same text already decomposed, where step 1 has only to copy", .strings = &.{ "Ma\u{0308}rtens", "Mo\u{0308}ller", "Mueller", "Æro\u{0338}", "A\u{030A}kerman", "C\u{030C}apek", "Dvor\u{030C}a\u{0301}k", "Gru\u{0308}n", "Hu\u{0308}ttner", "Ja\u{0308}ger", "Ko\u{0308}ge", "Lu\u{0308}beck", "No\u{0308}rga\u{030A}rd", "O\u{0308}land", "Pin\u{0303}eiro", "Quin\u{0303}ones", "Ruiz", "So\u{0308}rensen", "To\u{0308}rring", "Zu\u{0308}rich", }, }, .{ .name = "vietnamese", .why = "two marks a letter, so step 1 decomposes and then reorders", .strings = &.{ "Đà Nẵng", "Hà Nội", "Huế", "Cần Thơ", "Hải Phòng", "Vũng Tàu", "Nha Trang", "Quảng Ngãi", "Bắc Giang", "Hưng Yên", "Thái Bình", "Vĩnh Phúc", "Đắk Lắk", "Kiên Giang", "Sơn La", "Tuyên Quang", "Quảng Trị", "Bến Tre", "Cà Mau", "Điện Biên", }, }, .{ .name = "hangul", .why = "decomposes arithmetically to jamo, which no table lookup would find", .strings = &.{ "김철수", "이영희", "박민수", "최지우", "정해인", "강동원", "조정석", "윤아름", "장나라", "임시완", "한지민", "오연서", "서강준", "신민아", "권상우", "황정민", "안성기", "송강호", "전도연", "하정우", }, }, .{ .name = "han", .why = "nothing decomposes, and the weights are derived rather than looked up", .strings = &.{ "北京", "上海", "广州", "深圳", "成都", "杭州", "武汉", "西安", "南京", "重庆", "天津", "苏州", "长沙", "青岛", "大连", "厦门", "福州", "济南", "合肥", "昆明", }, }, .{ .name = "japanese", .why = "kana with voiced marks, which decompose, plus kanji that do not", .strings = &.{ "東京都", "大阪府", "ばんごう", "ぎじゅつ", "だいがく", "げんきん", "ずいひつ", "ぼうえき", "ぴあの", "ヴァイオリン", "がっこう", "でんしゃ", "ぶんがく", "ざっし", "じてんしゃ", "ぐんたい", "ぜんぶ", "どうぶつ", "べんとう", "ぽけっと", }, },};
/// Nanoseconds between two monotonic timestamps. `Io.Timestamp` counts in/// `i96`, which is wider than anything a benchmark needs.fn elapsed(from: std.Io.Timestamp, to: std.Io.Timestamp) u64 { return @intCast(@max(0, from.durationTo(to).nanoseconds));}
fn showShare( w: *std.Io.Writer, name: []const u8, whole: u64, step1: u64, through2: u64, n: usize,) !void { const ns = @as(f64, @floatFromInt(n)); const per = @as(f64, @floatFromInt(whole)) / ns; const step1_per = @as(f64, @floatFromInt(step1)) / ns; const through2_per = @as(f64, @floatFromInt(through2)) / ns; // Steps 1 and 2 are timed cumulatively, so step 2 is the difference and // step 3 is whatever the whole key costs beyond them. try w.print( " {s:<12} {d:>6.0} ns step 1 {d:>5.1} step 2 {d:>5.1} step 3 {d:>5.1} ({d:>4.1}%)\n", .{ name, per, step1_per, through2_per - step1_per, per - through2_per, 100.0 * (per - through2_per) / per, }, );}
/// What a key costs in bytes, per corpus.////// Section 9.1.4's run-length compression is applied to every level that/// repeats, so these are compressed sizes. What they were before that change,/// and what the techniques in 9.1 that are *not* applied would have been/// worth, is in `DESIGN.md` -- measured this same way, by writing the levels/// one at a time and counting the bytes.////// The fourth level is reported on its own because its cost depends on/// something other than the text: it is not written at the default strength/// at all, and at `quaternary` or `identical` it is a whole level of one/// repeated weight for any text without punctuation in it. Four bytes is the/// floor -- two of separator, two of the single synthetic weight such a level/// comes to.const Sizes = struct { bytes: usize = 0, level4: usize = 0,
fn add(sizes: *Sizes, bytes: []const u8) void { sizes.bytes += bytes.len; }};
pub fn main(init: std.process.Init.Minimal) !u8 { var gpa_state: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator();
var threaded: std.Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator();
const args = try init.args.toSlice(arena); const rounds: usize = if (args.len > 1) std.fmt.parseInt(usize, args[1], 10) catch 2000 else 2000;
// The fastest of a few passes rather than one, because a single pass is // noisy enough to move a share by ten points between runs -- which is // more than some of the differences this is here to measure. const repeats = 3;
var buffer: [4096]u8 = undefined; var stdout = std.Io.File.stdout().writer(io, &buffer); const w = &stdout.interface;
// The root collation, and a tailoring if one was built in. Which one does // not matter much -- what a tailored table changes is that step 2 looks in // two lists rather than one -- so the first that exists is taken. const tailored: ?collate.Table = blk: { const locales = collate.locales; inline for (@typeInfo(locales).@"struct".decl_names) |decl_name| { const field = @field(locales, decl_name); if (@TypeOf(field) != collate.Tailoring) continue; if (field.overrides.len == 0) continue; try w.print("tailoring: {s}\n", .{decl_name}); break :blk collate.cldr_root.tailored(&field); } break :blk null; };
const roots = [_]struct { []const u8, ?collate.Table }{ .{ "cldr root", if (collate.cldr_root.stage1.len != 0) collate.cldr_root else null }, .{ "tailored", tailored }, };
try w.print("{d} rounds over {d} strings a corpus\n", .{ rounds, corpora[0].strings.len });
// Without `-Dembed-cldr` there is no table to weigh anything with, and // every root below is skipped -- so say so rather than printing the // legend and no numbers, which looks like a benchmark that ran. if (roots[0][1] == null and roots[1][1] == null) { try w.print("\nno table was built in: pass -Dembed-cldr\n", .{}); try w.flush(); return 1; }
for (roots) |root| { const table = root[1] orelse continue; try w.print("\n{s}:\n", .{root[0]}); const c: collate.Collator = .{ .table = table };
for (corpora) |corpus| { var builder: collate.Builder = .empty; defer builder.deinit(gpa);
// The key goes into a buffer the caller keeps, through // `writeSortKeyUtf8`, rather than through `sortKeyAlloc`. An // allocation per key is what a benchmark would otherwise be // measuring: with a `DebugAllocator` behind it the first version // of this reported 21 microseconds a string and step 1 at 0.3%, // which is a number about the allocator. var key_buf: [4096]u8 = undefined;
// Warm, so that the first round's growth is not the measurement. for (corpus.strings) |s| { var kw: std.Io.Writer = .fixed(&key_buf); try builder.writeSortKeyUtf8(gpa, &kw, c, s); }
var whole_ns: u64 = std.math.maxInt(u64); for (0..repeats) |_| { const start = std.Io.Timestamp.now(io, .awake); for (0..rounds) |_| { for (corpus.strings) |s| { var kw: std.Io.Writer = .fixed(&key_buf); try builder.writeSortKeyUtf8(gpa, &kw, c, s); std.mem.doNotOptimizeAway(kw.end); } } whole_ns = @min(whole_ns, elapsed(start, std.Io.Timestamp.now(io, .awake))); }
var text: std.ArrayList(u21) = .empty; defer text.deinit(gpa); // Step 2 as well, so that what is left for step 3 -- writing the // weights out as a key -- can be read off as the remainder. That // is the part section 9.7's incremental comparison would skip // once a level has decided the answer. var step2_ns: u64 = std.math.maxInt(u64); for (0..repeats) |_| { const start = std.Io.Timestamp.now(io, .awake); for (0..rounds) |_| { for (corpus.strings) |s| { text.clearRetainingCapacity(); try collate.nfd.appendUtf8(&text, gpa, s); const ces = try builder.collationElements(gpa, c, text.items); std.mem.doNotOptimizeAway(ces.len); } } step2_ns = @min(step2_ns, elapsed(start, std.Io.Timestamp.now(io, .awake))); }
var step1_ns: u64 = std.math.maxInt(u64); for (0..repeats) |_| { const start = std.Io.Timestamp.now(io, .awake); for (0..rounds) |_| { for (corpus.strings) |s| { text.clearRetainingCapacity(); try collate.nfd.appendUtf8(&text, gpa, s); std.mem.doNotOptimizeAway(text.items.len); } } step1_ns = @min(step1_ns, elapsed(start, std.Io.Timestamp.now(io, .awake))); }
// And comparing two strings, which is what `order` is for: once // through the public entry point and once writing both keys into // buffers the caller keeps and reusing one `Builder` across the // lot. The gap between them is what hoisting a `Builder` buys, // which is what the API documentation advises for bulk work. // // `order` is timed with the *checking* allocator on purpose. It // used to allocate five times a comparison, which cost 30 // microseconds a pair here against 604 ns with an arena behind // it; it allocates nothing now, and the point of measuring it // this way is that the two numbers have converged. var pairs: usize = 0; var order_ns: u64 = std.math.maxInt(u64); for (0..repeats) |_| { const start = std.Io.Timestamp.now(io, .awake); pairs = 0; for (0..rounds) |_| { for (corpus.strings, 0..) |a, i| { const b = corpus.strings[(i + 1) % corpus.strings.len]; std.mem.doNotOptimizeAway(try c.order(gpa, a, b)); pairs += 1; } } order_ns = @min(order_ns, elapsed(start, std.Io.Timestamp.now(io, .awake))); }
var buffered_ns: u64 = std.math.maxInt(u64); var other_buf: [4096]u8 = undefined; for (0..repeats) |_| { const start = std.Io.Timestamp.now(io, .awake); for (0..rounds) |_| { for (corpus.strings, 0..) |a, i| { const b = corpus.strings[(i + 1) % corpus.strings.len]; var wa: std.Io.Writer = .fixed(&key_buf); try builder.writeSortKeyUtf8(gpa, &wa, c, a); var wb: std.Io.Writer = .fixed(&other_buf); try builder.writeSortKeyUtf8(gpa, &wb, c, b); std.mem.doNotOptimizeAway( collate.orderKeys(key_buf[0..wa.end], other_buf[0..wb.end]), ); } } buffered_ns = @min(buffered_ns, elapsed(start, std.Io.Timestamp.now(io, .awake))); }
try showShare( w, corpus.name, whole_ns, step1_ns, step2_ns, rounds * corpus.strings.len, ); // What a key costs in bytes, at the default strength and at // `quaternary`, which is the lowest strength that writes a fourth // level. Not timed, so it goes outside every timing loop. var sizes: Sizes = .{}; var quaternary_sizes: Sizes = .{}; { var level_buf: [8192]u8 = undefined; const quaternary: collate.Collator = .{ .table = c.table, .options = .{ .strength = .quaternary }, }; for (corpus.strings) |str| { try builder.weighUtf8(gpa, quaternary, str); for (0..4) |level| { var lw: std.Io.Writer = .fixed(&level_buf); try collate.sort_key.writeLevel( &lw, quaternary.options, quaternary.table.tailoring, builder.weighted.items, level, ); quaternary_sizes.add(level_buf[0..lw.end]); if (level == 3) sizes.level4 += lw.end; } } for (corpus.strings) |str| { try builder.weighUtf8(gpa, c, str); for (0..c.options.strength.levels()) |level| { var lw: std.Io.Writer = .fixed(&level_buf); try collate.sort_key.writeLevel( &lw, c.options, c.table.tailoring, builder.weighted.items, level, ); sizes.add(level_buf[0..lw.end]); } } }
const per_pair = @as(f64, @floatFromInt(order_ns)) / @as(f64, @floatFromInt(pairs)); const per_buffered = @as(f64, @floatFromInt(buffered_ns)) / @as(f64, @floatFromInt(pairs)); const strings = @as(f64, @floatFromInt(corpus.strings.len)); try w.print(" {s:<12} {d:>5.1} key bytes, {d:>5.1} at quaternary strength of which level 4 is {d:>5.1}\n", .{ "", @as(f64, @floatFromInt(sizes.bytes)) / strings, @as(f64, @floatFromInt(quaternary_sizes.bytes)) / strings, @as(f64, @floatFromInt(sizes.level4)) / strings, }); try w.print(" {s:<12} {d:>6.0} ns/pair through `order`, {d:>6.0} ns buffered\n", .{ "", per_pair, per_buffered, }); } }
try w.print("\nwhat each corpus is for:\n", .{}); for (corpora) |corpus| try w.print(" {s:<12} {s}\n", .{ corpus.name, corpus.why });
try w.flush(); return 0;}