unicode

Branch: main

Switch branches or tags

Branch: main
Go to file t

413 files indexed

History
Code

bench/xlang/site/dashboard.js
1// The performance dashboard. It reads two files next to the page:2// - snapshot.json: a full run of every harness, `results.json` of `bench/xlang`;3// - history.json: one entry per push to main, `compare.json` of4//   `bench/xlang --base` without its per-case costs, in the order recorded.5// Either may be missing; its sections then say so.6'use strict';78const IMPL = {9  "moonbit-native": { label: "MoonBit native", color: "--mb-native" },10  "moonbit-wasm-gc": { label: "MoonBit wasm-gc", color: "--mb-wasm" },11  "moonbit-wasm": { label: "MoonBit wasm", color: "--mb-wasm1" },12  "moonbit-js": { label: "MoonBit JS", color: "--mb-js" },13  "rust icu4x-utf16": { label: "ICU4X UTF-16", color: "--icu4x16" },14  "rust icu4x-utf8": { label: "ICU4X UTF-8", color: "--icu4x8" },15  "icu4c": { label: "ICU4C", color: "--icu4c" },16  "node": { label: "JS built-in", color: "--node" },17  "rust simd-normalizer": { label: "simd-normalizer", color: "--simd" },18  "rust idna": { label: "Rust idna", color: "--icu4x8" },19  "rust unicode-normalization": { label: "unicode-normalization", color: "--other" },20  "rust unicode-segmentation": { label: "unicode-segmentation", color: "--other" },21  "rust unicode-bidi": { label: "unicode-bidi", color: "--other" },22  "rust unicode-bidi-utf16": { label: "unicode-bidi (UTF-16)", color: "--other" },23  "rust std": { label: "Rust std", color: "--other" },24  "rust unicode-general-category": { label: "unicode-general-category", color: "--other" },25};26const ORDER = Object.keys(IMPL);27const BACKENDS = ["moonbit-native", "moonbit-wasm-gc", "moonbit-wasm", "moonbit-js"];2829const OPS = [30  ["norm/nfc", "NFC"], ["norm/nfd", "NFD"], ["norm/nfkc", "NFKC"], ["norm/nfkd", "NFKD"],31  ["norm/nfd>nfc", "NFD → NFC"], ["norm/is_nfc", "Is it NFC?"],32  ["seg/graphemes", "Grapheme clusters"], ["bidi/process", "Bidi levels"],33  ["idna/to_ascii", "IDNA ToASCII"], ["idna/to_unicode", "IDNA ToUnicode"],34  ["puny/encode", "Punycode encode"], ["puny/decode", "Punycode decode"],35  ["case/simple_upper", "Simple uppercase"], ["case/full_upper", "Full uppercase"],36  ["case/fold", "Case folding"], ["case/nfkc_casefold", "NFKC_Casefold"],37  ["prop/general_category_Ll", "General category"],38];39const OP_LABEL = Object.fromEntries(OPS);40const perCall = op => op.startsWith("idna/") || op.startsWith("puny/");41const unit = op => perCall(op) ? "ns / call" : "ns / code point";42const JS_API = {43  norm: "String.prototype.normalize", seg: "Intl.Segmenter",44  "idna/to_ascii": "url.domainToASCII", "idna/to_unicode": "url.domainToUnicode", puny: "node:punycode",45};4647// The repository, from the Pages address <owner>.github.io/<repository>/.48const REPO = (() => {49  const owner = location.hostname.endsWith(".github.io") ? location.hostname.split(".")[0] : "";50  const name = location.pathname.split("/").filter(Boolean)[0];51  return owner && name ? `https://github.com/${owner}/${name}` : "";52})();5354const css = name => `var(${name})`;55const el = (tag, attrs = {}, html = "") => {56  const e = document.createElement(tag);57  Object.assign(e, attrs);58  if (html) e.innerHTML = html;59  return e;60};61const escapeHtml = text => String(text).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);62const remember = (key, value) => { try { localStorage.setItem(key, value); } catch (e) {} };63const recall = key => { try { return localStorage.getItem(key); } catch (e) { return null; } };6465async function load(path) {66  try {67    const response = await fetch(path, { cache: "no-cache" });68    return response.ok ? await response.json() : null;69  } catch (e) {70    return null;71  }72}7374function fmt(v) {75  if (v == null) return "–";76  if (v >= 100) return Math.round(v).toString();77  if (v >= 10) return v.toFixed(1);78  if (v >= 1) return v.toFixed(2);79  return v.toFixed(v < 0.1 ? 3 : 2);80}81const fx = r => (r >= 10 ? r.toFixed(0) : r.toFixed(r >= 2 ? 1 : 2)) + "×";82const change = r => {83  const tenths = Math.round((r - 1) * 1000);84  return (tenths > 0 ? "+" : tenths < 0 ? "−" : "") + (Math.abs(tenths) / 10).toFixed(1) + "%";85};86function relWords(ratio) {87  // ratio = other / reference time. >1: reference is faster.88  if (ratio > 1.04) return { cls: "up", text: fx(ratio) + " faster" };89  if (ratio < 0.96) return { cls: "down", text: fx(1 / ratio) + " slower" };90  return { cls: "", text: "about even" };91}92// r = time / reference time. Faster is green, slower red, on a log scale that93// is full at `cap`.94function tint(r, cap, floor = 0.04) {95  if (!isFinite(r) || Math.abs(Math.log(r)) < floor) return "transparent";96  const a = Math.min(1, Math.abs(Math.log(r)) / Math.log(cap)) * 0.32 + 0.04;97  return r < 1 ? `rgba(var(--good-tint), ${a})` : `rgba(var(--bad-tint), ${a})`;98}99100// Chips that pick one of `options` ([value, label]); `onPick` gets the value.101function chips(target, options, current, onPick) {102  const group = document.getElementById(target);103  group.innerHTML = "";104  for (const [value, label] of options) {105    const b = el("button", { className: "chip", type: "button" }, escapeHtml(label));106    b.setAttribute("aria-pressed", value === current);107    b.onclick = () => {108      [...group.children].forEach(c => c.setAttribute("aria-pressed", c === b));109      onPick(value);110    };111    group.appendChild(b);112  }113}114115// ---------------------------------------------------------------- history116117// A commit of a history entry as a link, with the pull request it merged.118// `pick` is the checkbox that ticks the entry for combining.119function commitCell(commit, pick = "") {120  const sha = commit.commit || "";121  const short = sha.slice(0, 7);122  const subject = commit.subject || "";123  const merge = subject.match(/^Merge pull request #(\d+) from /);124  const squash = subject.match(/\(#(\d+)\)$/);125  const pr = merge ? merge[1] : squash ? squash[1] : null;126  const title = merge && commit.title ? commit.title : subject;127  const shaHtml = REPO && sha128    ? `<a class="sha" href="${REPO}/commit/${sha}">${short}</a>` : `<span class="sha">${short}</span>`;129  const titleHtml = REPO && pr130    ? `<a href="${REPO}/pull/${pr}">${escapeHtml(title)}</a>` : escapeHtml(title);131  const when = (commit.date || "").slice(0, 10);132  return `<td class="commit">${pick}${shaHtml}${titleHtml}<span class="when">${when}${commit.dirty ? " · uncommitted changes" : ""}</span></td>`;133}134135// A change in time as a cell: greyed out within `noise`, a ratio itself.136function changeCell(r, noise, title = "") {137  if (r == null) return `<td class="muted">–</td>`;138  const t = title ? ` title="${escapeHtml(title)}"` : "";139  return Math.abs(r - 1) <= noise140    ? `<td class="change quiet"${t}>${change(r)}</td>`141    : `<td class="change"${t} style="background:${tint(r, 1.5, 0)}">${change(r)}</td>`;142}143144function renderHistory(history) {145  const body = document.getElementById("history-body");146  // Newest first. Runs may finish out of order, so sort by commit date.147  const runs = (history || []).slice().reverse().sort((a, b) =>148    Date.parse(b.about?.head?.date || 0) - Date.parse(a.about?.head?.date || 0));149  if (!runs.length) {150    document.getElementById("backend-chips").closest(".controls").hidden = true;151    body.appendChild(el("p", { className: "empty" },152      "No runs yet. Each merge to main adds one once the benchmark workflow has run."));153    return;154  }155  const present = BACKENDS.filter(b => runs.some(run => Object.values(run.operations || {}).some(r => b in r)));156  let backend = recall("ub-backend");157  if (!present.includes(backend)) backend = present[0];158  const LIMIT = 30;159  let showAll = false;160  const shaOf = run => run.about?.head?.commit || "";161  const baseOf = run => run.about?.base?.commit || "";162  // Changes within the noise of a run are greyed out; 2% at least.163  const noiseOf = run => Math.max(0.02, (run.spread?.[backend] ?? 1) - 1);164165  // The merges combined: rows lo..hi of `runs`, newest first, always one166  // unbroken stretch, so that together they are the change over a range of167  // main. The address keeps it as #range=<base>..<head>, in git's sense: the168  // merges after <base> up to <head>.169  let range = null;170  const readRange = () => {171    range = null;172    const wanted = new URLSearchParams(location.hash.slice(1)).get("range") || "";173    const [from, to] = wanted.split("..");174    if (!from || !to || from.length < 4 || to.length < 4) return;175    const hi = runs.findIndex(run => baseOf(run).startsWith(from));176    const lo = runs.findIndex(run => shaOf(run).startsWith(to));177    if (lo < 0 || hi < lo) return;178    range = { lo, hi };179    if (hi >= LIMIT) showAll = true;180  };181  readRange();182  const saveRange = () => {183    const hash = range ? `#range=${baseOf(runs[range.hi]).slice(0, 7)}..${shaOf(runs[range.lo]).slice(0, 7)}` : "";184    try { window.history.replaceState(null, "", location.pathname + location.search + hash); } catch (e) {}185  };186187  // The costs of every case of a run, `runs/<head>.json`, fetched once.188  const costs = new Map();189  const costsOf = run => {190    const sha = shaOf(run);191    if (!costs.has(sha)) {192      costs.set(sha, { state: "loading" });193      load(`runs/${sha}.json`).then(data => {194        costs.set(sha, data?.cases ? { state: "done", cases: data.cases } : { state: "missing" });195        draw();196      });197    }198    return costs.get(sha);199  };200201  // The combined change of the range, per operation. Each run times its base202  // and head on one runner, but different runs land on different machines, so203  // times cannot be compared across runs, only ratios. Per case, the ratios of204  // the runs multiply into the change from the base of the oldest to the head205  // of the newest; the geometric mean over the cases that every run measured206  // gives the operation's. Cases some run lacks, because the harness added207  // them within the range, are left out. Without the costs of a run, it falls208  // back on multiplying the runs' means, which differ from the per-case figure209  // only where the inputs changed. Noise adds up too: in log space, as the210  // root of the sum of squares.211  const combinedRow = ops => {212    if (!range || range.hi === range.lo) return "";213    const chosen = runs.slice(range.lo, range.hi + 1);214    const all = chosen.map(costsOf);215    const loading = all.some(c => c.state === "loading");216    const perCase = all.every(c => c.state === "done");217    // Pushes that were never compared (they changed no library code, or their218    // run failed) leave a run whose base is not the head of the one before.219    const gaps = chosen.filter((run, k) => k < chosen.length - 1 && baseOf(run) !== shaOf(chosen[k + 1])).length;220    const noise = Math.expm1(Math.sqrt(chosen.reduce((a, run) => a + Math.log1p(noiseOf(run)) ** 2, 0)));221    const from = baseOf(chosen[chosen.length - 1]);222    const to = shaOf(chosen[0]);223    const label = `${from.slice(0, 7)} → ${to.slice(0, 7)}`;224    const span = REPO && from && to ? `<a href="${REPO}/compare/${from}...${to}">${label}</a>` : label;225    const notes = [];226    if (gaps) notes.push(`${gaps} push${gaps > 1 ? "es" : ""} between them ${gaps > 1 ? "were" : "was"} not compared and count${gaps > 1 ? "" : "s"} as no change`);227    if (!loading && !perCase) notes.push("some per-case costs are missing, so this multiplies the merges' means");228    let dropped = false;229    const cells = ops.map(([op]) => {230      if (loading) return `<td class="muted">…</td>`;231      if (!perCase) {232        const rs = chosen.map(run => run.operations?.[op]?.[backend]);233        if (rs.some(r => r == null)) return `<td class="muted" title="not measured by every merge">–</td>`;234        return changeCell(Math.exp(rs.reduce((a, r) => a + Math.log(r), 0)), noise);235      }236      const prefix = op + "/";237      const names = new Set();238      for (const c of all) for (const name of Object.keys(c.cases)) if (name.startsWith(prefix)) names.add(name);239      const logs = [];240      for (const name of names) {241        let sum = 0;242        const complete = all.every(c => {243          const [base, head] = c.cases[name]?.[backend] || [];244          if (!(base > 0 && head > 0)) return false;245          sum += Math.log(head / base);246          return true;247        });248        if (complete) logs.push(sum);249      }250      if (!logs.length) return `<td class="muted" title="not measured by every merge">–</td>`;251      const partial = logs.length < names.size;252      dropped ||= partial;253      const r = Math.exp(logs.reduce((a, x) => a + x, 0) / logs.length);254      return changeCell(r, noise, partial ? `over the ${logs.length} of ${names.size} inputs that every merge measured` : "");255    }).join("");256    if (dropped) notes.push("inputs added within the range are left out; hover a cell for how many");257    return `<tr class="combined"><td class="commit"><span class="label">Combined · ${chosen.length} merges</span>` +258      `<span class="when">${span} · noise ±${(noise * 100).toFixed(1)}%</span>` +259      notes.map(n => `<span class="when">${n}</span>`).join("") + `</td>${cells}</tr>`;260  };261262  const draw = () => {263    const ops = OPS.filter(([op]) => runs.some(run => run.operations?.[op]?.[backend] != null));264    const shown = showAll ? runs : runs.slice(0, LIMIT);265    const head = `<thead><tr><th>merge</th>${ops.map(([, label]) => `<th class="op">${label}</th>`).join("")}</tr></thead>`;266    const rows = shown.map((run, i) => {267      const sha = shaOf(run);268      const on = range != null && i >= range.lo && i <= range.hi;269      const pick = `<input type="checkbox" class="pick" data-index="${i}"${on ? " checked" : ""} aria-label="Combine ${escapeHtml(sha.slice(0, 7))}">`;270      const cells = ops.map(([op]) => changeCell(run.operations?.[op]?.[backend], noiseOf(run))).join("");271      return `<tr${on ? ` class="picked"` : ""}>${commitCell(run.about?.head || {}, pick)}${cells}</tr>`;272    }).join("");273    body.innerHTML = `<div class="table-scroll history"><table>${head}<tbody>${combinedRow(ops)}${rows}</tbody></table></div>`;274    if (runs.length > LIMIT && !showAll) {275      const more = el("button", { className: "chip more", type: "button" }, `Show all ${runs.length} merges`);276      more.onclick = () => { showAll = true; draw(); };277      body.appendChild(more);278    }279  };280  const setRange = next => {281    range = next;282    saveRange();283    draw();284  };285  // Ticking a merge stretches the range to it, ticking every merge between.286  // Unticking one at an end shrinks the range by it; unticking one inside287  // drops it and every older merge, keeping the newer end.288  body.addEventListener("click", event => {289    const box = event.target.closest("input.pick");290    if (!box) return;291    const i = Number(box.dataset.index);292    if (box.checked) {293      setRange(range ? { lo: Math.min(range.lo, i), hi: Math.max(range.hi, i) } : { lo: i, hi: i });294    } else if (range.lo === range.hi) {295      setRange(null);296    } else if (i === range.hi) {297      setRange({ lo: range.lo, hi: i - 1 });298    } else if (i === range.lo) {299      setRange({ lo: i + 1, hi: range.hi });300    } else {301      setRange({ lo: range.lo, hi: i - 1 });302    }303    body.querySelector(`input.pick[data-index="${i}"]`)?.focus();304  });305  const combine = document.getElementById("combine-chips");306  combine.innerHTML = "";307  for (const n of [2, 3, 5, 10].filter(n => n <= runs.length)) {308    const b = el("button", { className: "chip", type: "button" }, `Last ${n}`);309    b.onclick = () => setRange({ lo: 0, hi: n - 1 });310    combine.appendChild(b);311  }312  const none = el("button", { className: "chip", type: "button" }, "None");313  none.onclick = () => setRange(null);314  combine.appendChild(none);315316  // A link to another range, opened in this tab, changes only the hash.317  window.addEventListener("hashchange", () => { readRange(); draw(); });318319  chips("backend-chips", present.map(b => [b, IMPL[b].label.replace("MoonBit ", "")]), backend, value => {320    backend = value;321    remember("ub-backend", value);322    draw();323  });324  draw();325}326327// --------------------------------------------------------------- snapshot328329function renderSnapshotMeta(about) {330  const commit = about.commit || {};331  const parts = [];332  if (commit.commit) {333    const short = commit.commit.slice(0, 7);334    const label = `${short}${commit.dirty ? " with uncommitted changes" : ""}`;335    parts.push(REPO ? `<a href="${REPO}/commit/${commit.commit}" style="color:inherit">${label}</a>` : label);336  }337  if (about.machine) parts.push(escapeHtml(about.machine));338  for (const [name, version] of Object.entries(about.versions || {})) {339    parts.push(escapeHtml(version.toLowerCase().startsWith(name.toLowerCase()) ? version : `${name} ${version}`));340  }341  if (about.rounds) parts.push(`fastest of ${about.rounds} rounds`);342  if (about.date) parts.push(escapeHtml(about.date.slice(0, 10)));343  document.getElementById("snapshot-meta").innerHTML = parts.map(p => `<span>${p}</span>`).join("");344}345346function renderSnapshot(snapshot) {347  if (!snapshot || !snapshot.cases) {348    document.getElementById("snapshot-meta").replaceWith(el("p", { className: "empty" },349      "No snapshot has been published yet. Copy <code>_build/xlang/results.json</code> of a full run to <code>bench/xlang/site/snapshot.json</code>."));350    for (const id of ["icu4x", "js", "cases"]) document.getElementById(id).hidden = true;351    return;352  }353  renderSnapshotMeta(snapshot.about || {});354  const DATA = snapshot.cases;355  // Only implementations that take UTF-16 strings, so every comparison reads356  // the same bytes. Cases left with no peer for MoonBit are dropped.357  const UTF16 = new Set(["moonbit-native", "moonbit-wasm-gc", "moonbit-wasm", "moonbit-js", "rust icu4x-utf16", "icu4c", "node", "rust unicode-bidi-utf16"]);358  for (const [key, row] of Object.entries(DATA)) {359    for (const impl of Object.keys(row)) if (!UTF16.has(impl)) delete row[impl];360    if (!Object.keys(row).some(i => !i.startsWith("moonbit-"))) delete DATA[key];361  }362  // op -> { input -> { impl -> ns } }363  const byOp = {};364  for (const [key, row] of Object.entries(DATA)) {365    const [g, o, ...rest] = key.split("/");366    (byOp[g + "/" + o] ||= {})[rest.join("/")] = row;367  }368  const geomean = (op, impl) => {369    const vals = Object.values(byOp[op] || {}).map(r => r[impl]).filter(v => v != null);370    if (!vals.length) return null;371    return Math.exp(vals.reduce((a, v) => a + Math.log(v), 0) / vals.length);372  };373  const legend = (target, impls) => {374    document.getElementById(target).innerHTML = impls375      .map(i => `<span><i style="background:${css(IMPL[i].color)}"></i>${IMPL[i].label}</span>`).join("");376  };377  const card = (op, impls, ref, opts = {}) => {378    const vals = impls.map(i => [i, geomean(op, i)]).filter(([, v]) => v != null);379    const refVal = geomean(op, ref);380    if (!vals.length || refVal == null) return null;381    const max = Math.max(...vals.map(([, v]) => v));382    const c = el("article", { className: "card" });383    c.appendChild(el("div", { className: "card-head" }, `<h3>${OP_LABEL[op]}</h3><span class="unit">${unit(op)}</span>`));384    if (opts.api) c.appendChild(el("div", { className: "api" }, opts.api));385    const bars = el("div", { className: "bars" });386    for (const [i, v] of vals) {387      const r = el("div", { className: "bar" + (i === ref ? " ref" : "") });388      const rel = i === ref ? "" : ` <small>${fx(v / refVal)}</small>`;389      r.innerHTML = `<span class="name" title="${IMPL[i].label}">${IMPL[i].label}</span>390        <span class="track"><span class="fill" style="width:${Math.max(1.5, (v / max) * 100)}%;background:${css(IMPL[i].color)}"></span></span>391        <span class="val">${fmt(v)}${rel}</span>`;392      bars.appendChild(r);393    }394    c.appendChild(bars);395    if (opts.verdict) {396      const verdict = opts.verdict(refVal);397      if (verdict) c.appendChild(el("p", { className: "verdict" }, verdict));398    }399    return c;400  };401402  // Against ICU403  const ICU_IMPLS = ["moonbit-native", "moonbit-wasm-gc", "moonbit-wasm", "rust icu4x-utf16", "icu4c", "rust unicode-bidi-utf16"];404  legend("legend-icu", ICU_IMPLS.filter(i => Object.values(DATA).some(row => i in row)));405  const gridIcu = document.getElementById("grid-icu");406  const ICU_OPS = ["norm/nfc", "norm/nfd", "norm/nfkc", "norm/nfkd", "norm/nfd>nfc", "norm/is_nfc", "seg/graphemes",407    "bidi/process", "idna/to_ascii", "idna/to_unicode", "case/simple_upper", "prop/general_category_Ll"];408  for (const op of ICU_OPS) {409    const rivals = ["rust icu4x-utf16", "icu4c", "rust unicode-bidi-utf16"]410      .map(i => [i, geomean(op, i)]).filter(([, v]) => v != null).sort((a, b) => a[1] - b[1]);411    const c = card(op, ICU_IMPLS, "moonbit-native", {412      api: op === "bidi/process" ? "ICU4X has no bidi resolver in this harness"413        : op.startsWith("idna") || op.startsWith("case") || op.startsWith("prop") ? "ICU4X is measured here only on UTF-8" : "",414      verdict: refVal => {415        if (!rivals.length) return "";416        const [best, bv] = rivals[0];417        const w = relWords(bv / refVal);418        return `MoonBit native vs ${IMPL[best].label}, the fastest of the others: <b class="${w.cls}">${w.text}</b>`;419      },420    });421    if (c) gridIcu.appendChild(c);422  }423424  // JS425  const JS_OPS = ["norm/nfc", "norm/nfd", "norm/nfkc", "norm/nfkd", "norm/nfd>nfc", "seg/graphemes",426    "idna/to_ascii", "idna/to_unicode", "puny/encode", "puny/decode"];427  legend("legend-js", ["moonbit-js", "node", "moonbit-native"]);428  const gridJs = document.getElementById("grid-js");429  for (const op of JS_OPS) {430    const api = JS_API[op] || JS_API[op.split("/")[0]];431    const c = card(op, ["moonbit-js", "node", "moonbit-native"], "moonbit-js", {432      api: "built-in: " + api,433      verdict: refVal => {434        const node = geomean(op, "node");435        if (node == null) return "";436        const w = relWords(node / refVal);437        return `MoonBit JS vs <code>${api}</code>: <b class="${w.cls}">${w.text}</b>`;438      },439    });440    if (c) gridJs.appendChild(c);441  }442  if (!gridJs.children.length) document.getElementById("js").hidden = true;443444  // Findings: [ratio, text], where ratio = time of b / time of a.445  const ratio = (op, a, b) => {446    const x = geomean(op, a), y = geomean(op, b);447    return x != null && y != null ? y / x : null;448  };449  const findings = [450    [ratio("norm/nfd>nfc", "moonbit-native", "rust icu4x-utf16"), "ICU4X (UTF-16) at composing NFD into NFC, MoonBit native, geometric mean over the corpora"],451    [ratio("norm/nfd", "moonbit-native", "rust icu4x-utf16"), "ICU4X (UTF-16) at NFD, which forces every character through decomposition"],452    [ratio("idna/to_ascii", "moonbit-native", "icu4c"), "ICU4C at IDNA ToASCII, MoonBit native, per call"],453    [ratio("norm/nfc", "moonbit-wasm", "moonbit-wasm-gc"), "wasm-gc at NFC with the wasm backend, which compiles the SIMD scan to simd128"],454    [ratio("seg/graphemes", "moonbit-js", "node"), "Intl.Segmenter at grapheme clusters, with MoonBit compiled to plain JavaScript"],455    [ratio("norm/nfd", "moonbit-js", "node"), "String.prototype.normalize at NFD on the JS backend, where V8 calls into C++ ICU"],456  ].filter(([r]) => r != null);457  document.getElementById("findings").innerHTML = findings.map(([r, text]) => {458    const [n, word] = r >= 1 ? [fx(r), "faster than"] : [fx(1 / r), "slower than"];459    return `<div class="finding"><b>${n}</b><span>${word} ${text}</span></div>`;460  }).join("");461462  // Every case463  const baseSel = document.getElementById("baseline");464  const SHOWN_OPS = OPS.filter(([op]) => byOp[op]);465  let curOp = recall("ub-op");466  if (!byOp[curOp]) curOp = byOp["norm/nfd>nfc"] ? "norm/nfd>nfc" : SHOWN_OPS[0]?.[0];467  const implsFor = op => {468    const present = new Set();469    for (const row of Object.values(byOp[op])) Object.keys(row).forEach(k => present.add(k));470    return ORDER.filter(i => present.has(i));471  };472  const renderTable = () => {473    if (!curOp) return;474    const impls = implsFor(curOp);475    const prev = baseSel.value;476    baseSel.innerHTML = impls.map(i => `<option value="${i}">${IMPL[i].label}</option>`).join("");477    baseSel.value = impls.includes(prev) ? prev : impls.includes("moonbit-native") ? "moonbit-native" : impls[0];478    const base = baseSel.value;479    const rows = byOp[curOp];480    const inputs = Object.keys(rows).sort((a, b) => a.localeCompare(b));481    const head = `<thead><tr><th>input <span class="muted" style="font-weight:400">(${unit(curOp)})</span></th>${impls.map(i =>482      `<th><span class="sw" style="background:${css(IMPL[i].color)}"></span>${IMPL[i].label}</th>`).join("")}</tr></thead>`;483    const cell = (v, b) => {484      if (v == null) return `<td class="muted">–</td>`;485      const r = v / b;486      return `<td style="background:${tint(r, 8)}">${fmt(v)}<span class="r">${isFinite(r) ? r.toFixed(2) + "×" : ""}</span></td>`;487    };488    const body = inputs.map(name => `<tr><td>${escapeHtml(name.replace(/^TestNames_/, "Names · "))}</td>${impls.map(i => cell(rows[name][i], rows[name][base])).join("")}</tr>`).join("");489    const gm = `<tr class="gm"><td>geometric mean</td>${impls.map(i => cell(geomean(curOp, i), geomean(curOp, base))).join("")}</tr>`;490    document.getElementById("case-table").innerHTML = head + `<tbody>${body}${gm}</tbody>`;491  };492  chips("op-chips", SHOWN_OPS, curOp, op => { curOp = op; remember("ub-op", op); renderTable(); });493  baseSel.onchange = renderTable;494  renderTable();495  document.getElementById("case-count").textContent = `All ${Object.keys(DATA).length} cases`;496}497498Promise.all([load("snapshot.json"), load("history.json")]).then(([snapshot, history]) => {499  renderHistory(history);500  renderSnapshot(snapshot);501});502