From 33742af59c8334653c6e7370f499bf512f91c6c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:17:01 +0000 Subject: [PATCH] docs(adr): draft ADR-0028, what a string index counts (#831) A draft decision record for the owner. It changes no semantics. - Usage of len, string_get, string_sub, string_char_code_at and char_to_int across the repository, the stdlib and the satellites, with the len sites classified by argument type. - A Bun benchmark of candidate lowerings (UTF-16 units, octets with and without a cached UTF-8 view, code points, a Uint8Array representation) and a wasm measurement of the boundary check. - Five options with migration cost, Char interaction, wasm cost and proof-friendliness, rated, with a recommendation. Refs #831 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01J4QvDhJog6g9kprphCAadr --- docs/NAVIGATION.adoc | 1 + docs/decisions/0028-string-index-units.adoc | 626 ++++++++++++++++++++ 2 files changed, 627 insertions(+) create mode 100644 docs/decisions/0028-string-index-units.adoc diff --git a/docs/NAVIGATION.adoc b/docs/NAVIGATION.adoc index d9a5b1f3..278581b9 100644 --- a/docs/NAVIGATION.adoc +++ b/docs/NAVIGATION.adoc @@ -54,6 +54,7 @@ This guide helps you navigate the AffineScript repository structure. * link:ULTRAPLAN.adoc[Ultraplan — Mass Recon & Strategic Plan] - **NEW 2026-09-25** — ecosystem topology systemet→anytype→affinescript→faces, mathematical foundations, rename assessment, phased execution (do-nothing plan only) * link:decisions/0027-systemet-rename-to-system-et.adoc[ADR-027: systemet→system-et Rename Assessment] - **NEW 2026-09-25** — blast radius, options, recommendation (Option A: keep systemet repo, display as system-et) +* link:decisions/0028-string-index-units.adoc[ADR-0028: What a string index counts] - **DRAFT 2026-12-01, awaiting owner decision (#831)** — octets, code points or UTF-16 units: usage counts, Bun benchmark, options and recommendation * link:specs/affinescript-spec.md[AffineScript Specification] - Complete language spec * link:specs/SPEC.adoc[Core Specification] - Core language features diff --git a/docs/decisions/0028-string-index-units.adoc b/docs/decisions/0028-string-index-units.adoc new file mode 100644 index 00000000..4dabc149 --- /dev/null +++ b/docs/decisions/0028-string-index-units.adoc @@ -0,0 +1,626 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += ADR-0028: What a string index counts +Jonathan D.A. Jewell +:toc: +:toclevels: 2 +:icons: font + +Status:: *DRAFT — awaiting owner decision* (issue #831). Nothing here is implemented. No semantics change in this PR. +Date:: 2026-12-01 +Series:: Settled-decisions ledger. Builds on PR #829 (`docs/UNICODE-STRINGS.adoc`, open at the time of writing), which measured the divergence and added three backend-independent primitives without changing the old ones. + +== Context + +`len`, `string_length`, `string_get`, `string_sub` and `string_char_code_at` +take and return `Int` positions in a `String`. What a position counts depends +on the backend: + +[cols="3,2,2,2",options="header"] +|=== +| Probe | interp (`eval`) | core wasm | Bun-ESM + +| `len("é")` | 2 | 2 | 1 +| `len("🦜")` | 4 | 4 | 2 +| `string_char_code_at("🦜", 0)` | 240 | 240 | 55358 (a lone surrogate) +|=== + +(Measured on `main` `ee211d3` for #831; the full table is in +`docs/UNICODE-STRINGS.adoc`.) The interpreter and core wasm hold a string as +UTF-8 octets and index by octet. Bun-ESM holds a JS string and indexes by +UTF-16 code unit (`lib/codegen_deno.ml:612-617`, `:1240-1261`). A well-typed +program prints different values on different backends and nothing fails. + +Three further facts frame the decision: + +* `string_sub` can cut a character in half on every backend, and the result + is not a sequence of Unicode scalar values. +* A `Char` is one octet in the AST (`LitChar of char`, `lib/ast.ml:102`), so + `'é'` is a lexer error (`lib/lexer.ml:345`). +* The estate DEED printer must count line length in UTF-8 octets (a DEED line + is at most 998 octets) and a later formal round-trip proof of that printer + will rest on that count. + +== Evidence 1: how the builtins are used + +Measured on `main` `4248912` over every tracked `.affine` file (575 files). +Commands are in <>. + +=== Call sites + +Occurrences of `name(` outside comment lines: + +[cols="3,1,1,1",options="header"] +|=== +| Builtin | `stdlib/` | satellites (`affinescript-*`) | `tests/` + `test/` + +| `len` | 51 | 48 | 33 +| `string_length` | 1 | 0 | 25 +| `string_get` | 11 | 0 | 0 +| `string_sub` | 23 | 0 | 13 +| `string_char_code_at` | 6 | 0 | 39 +| `char_to_int` | 8 | 0 | 1 +| `string_find` | 6 | 0 | 10 +|=== + +`examples/`, `packages/`, `editors/`, `tools/`, `bench/`, `docs/`, +`conformance/` and `proposals/` have none. + +`len` is overloaded on arrays and strings, so I classified its 132 sites by +reading each one: + +[cols="3,1,1,1",options="header"] +|=== +| `len` argument | `stdlib/` | satellites | tests + +| a `String` | 29 | 0 | 19 +| an array | 22 | 48 | 7 +| a user function or local named `len` | 0 | 0 | 7 +|=== + +So 48 of 132 `len` sites are on strings, and *no satellite calls any of these +builtins on a string*: all 48 satellite sites are array lengths (`Crdt`, +`Router`, `Tea`). + +=== Non-ASCII data + +No tracked `.affine` program applies an index builtin to a non-ASCII literal. +Two files hold non-ASCII string literals at all +(`tests/codegen-deno/non_ascii.affine`, `tests/conformance/run_all.affine`), +and neither indexes them. No `.mjs` harness passes non-ASCII text to a +function that indexes it. On ASCII data the three backends agree, which is why +the divergence was not caught by a test. + +=== Byte-oriented code that depends on the unit + +Three stdlib modules treat a string as bytes. On octet backends they are +correct. On Bun-ESM they are silently wrong for non-ASCII input today: + +[cols="2,3,3",options="header"] +|=== +| Code | core wasm (octets) | Bun-ESM (UTF-16 units) + +| `encoding::to_base64("é")` | `w6k=` (correct: RFC 4648 over UTF-8) | `6Q==` (the Latin-1 byte `0xE9`) +| `encoding::to_base64("🦜")` | `8J+mnA==` (correct) | `P5w=` (surrogates truncated to 8 bits; not decodable to the input) +|=== + +The same holds by construction for `SafeHex` (hex of +`char_to_int(string_get(s, i))`, `stdlib/SafeHex.affine:63`, and the +constant-time compare at `:92-93`) and for JSON escaping +(`stdlib/json.affine:176-196`), which walk the string one unit at a time. I +ran only the base64 probe. + +=== The per-unit slice idiom + +Ten stdlib sites take `string_sub(s, i, 1)`: + +* 4 index a fixed ASCII table (`SafeHex.affine:12`, `encoding.affine:27`, + `:110`, `json.affine:166`). Any option leaves them alone. +* 2 walk input that is ASCII by contract (`encoding.affine:73` hex, + `:185` base64). +* 4 walk arbitrary text (`io.affine:55`, `json.affine:196`, + `string.affine:131`, `:182`). On octet backends these cut every non-ASCII + character into single octets and rely on `++` gluing them back. + +=== What I could not measure + +* The interpreter cannot run the stdlib loops at all: `let mut i = 0; i = i + 1;` + stops with `Type mismatch: Expected mutable reference`. This is the known + `let mut` gap in `docs/CAPABILITY-MATRIX.adoc`. Octet-side stdlib results + above are from core wasm, with the module inlined into one file because + stdlib modules do not link on wasm. +* Estate code outside this repository (the DEED printer, kyX) was not + searched; this session has access to this repository only. + +== Evidence 2: cost on Bun + +A throwaway benchmark of candidate lowerings, run under Bun 1.4.4 on Linux +x64 (4 vCPU Xeon 2.3 GHz, shared container). Median of three runs; wall +clock; no statistical treatment. The script is in <>. + +Candidates: + +[horizontal] +U16:: today's lowering: `.length`, `charCodeAt`, `slice`. +A-naive:: octets; `TextEncoder.encode` on every call. +A-cache:: octets through a one-entry cache of the last string's UTF-8 view, with an all-ASCII fast path (octet index = UTF-16 index). +A-byteLength:: `len` only, via `Buffer.byteLength(s, "utf8")`; no allocation, no cache. +B-naive:: code points; walk from the start on every call. +B-cache:: code points through a one-entry cache of `Array.from(s)`. +E-bytes:: `String` is a `Uint8Array` of UTF-8 (#831 option 3). + +Inputs: `ascii` is English text; `mixed` repeats `aé漢🦜 naïve` (1-, 2-, 3- and +4-octet characters). `1k` is about 1 000 UTF-16 units, `100k` about 100 000. + +[cols="4,2,2,2,2,2,2,2",options="header"] +|=== +| Workload | U16 | A-naive | A-cache | A-byteLength | B-naive | B-cache | E-bytes + +| W1 `len`, string not in cache, ascii-1k | 37 ns | 658 ns | 718 ns | 71 ns | 694 ns | 12.6 µs | 42 ns +| W1 same, ascii-100k | 52 ns | 29.2 µs | 27.4 µs | 4.6 µs | 66.9 µs | 728 µs | 40 ns +| W1 same, mixed-100k | 52 ns | 44.6 µs | 42.0 µs | 11.6 µs | 268 µs | 812 µs | 37 ns +| W1b `len`, same string again, any input | — | — | 39 ns | — | — | 40 ns | — +| W2 scan (`len` once, then `string_char_code_at` at every index), ascii-1k | 478 ns | 671 µs | 3.3 µs | — | 417 µs | 3.4 µs | 368 ns +| W2 same, mixed-1k | 2.7 µs | 505 µs | 6.5 µs | — | 1.09 ms | 4.6 µs | 6.0 µs +| W2 same, ascii-100k | 323 µs | — | 609 µs | — | — | 691 µs | 533 µs +| W2 same, mixed-100k | 323 µs | — | 620 µs | — | — | 466 µs | 402 µs +| W3 rebuild by `out ++ string_sub(s, i, 1 char)`, ascii-1k | 19.4 µs | 1.60 ms | 23.4 µs | — | 967 µs | 60.7 µs | 436 µs +| W3 same, mixed-1k | 13.7 µs | 708 µs | 76.1 µs | — | 3.07 ms | 30.6 µs | 225 µs +| W4 200 appends with `len` after each, ascii-1k | 3.5 µs | — | 474 µs | 264 µs | — | 5.96 ms | 290 µs +| W4 same, mixed-1k | 3.3 µs | — | 781 µs | 489 µs | — | 8.16 ms | 291 µs +| W5 hand a string to the host (`println`, any extern), mixed-100k | 37 ns | 37 ns | 37 ns | — | 37 ns | 37 ns | 68.1 µs +|=== + +In W2 on `mixed` the candidates do different amounts of work: 660 UTF-16 +units, 1 140 octets or 600 code points per 1k string. + +What the numbers say: + +* *A re-encode per call is not viable.* A-naive and B-naive turn the ordinary + scan loop quadratic: 190 to 1 400 times slower than today at 1 k. +* *A one-entry cache makes the scan loop cheap.* A-cache costs about 1.9 + times today's scan at 100 k, and 2.4 to 7 times at 1 k (3 ns per character + in absolute terms). +* *`len` stops being O(1) under every octet or code-point option on a JS + string.* The first `len` of a string is O(n): 4.6 to 11.6 µs per 100 k with + `Buffer.byteLength`. The pattern that suffers is `len` inside a loop that + also grows the string (W4): 75 to 150 times slower than today, because each + call flattens and measures a new string. `stdlib/encoding.affine:48` + (`while len(s) < width`) has that shape, on short strings. +* *Code points cost more than octets to cache* (12.6 µs against 0.7 µs to + build the view of a 1 k string) and far more in W4. +* *A `Uint8Array` representation fixes `len` and indexing but moves the cost + to concatenation and the host boundary.* Every `++` copies (W3: 16 to 22 + times slower than today; W4: about 85 times), and every string handed to + the host is decoded (68 µs per 100 k). 227 of the 559 `extern fn` + declarations in tracked `.affine` files have `String` in their signature; + each would need a transcode. + +Limits: one machine, one Bun version, three runs. The cache is one entry, so +two strings scanned in alternation would miss on every call; I did not +measure that. A JS `!==` on strings compares content, so a cache check +against an equal-length different string is O(n) in the worst case. + +== Evidence 3: cost on core wasm + +Octet indexing is what wasm does today: one `i32.load8_u`. A boundary check +adds one more load and a compare, `(b & 0xC0) != 0x80`, at each offset passed +to `string_sub` or `string_get`. + +Measured by writing that check in AffineScript and scanning a 216-octet +literal 200 000 times (43.2 M index operations), under `bun run`: + +[cols="3,2",options="header"] +|=== +| Program | Wall clock (three runs) + +| loop only, no index | 29–37 ms +| `string_char_code_at(s, i)` | 51–58 ms +| the same plus the boundary test | 76–87 ms +|=== + +So about 0.5 ns per octet read and at most about 0.6 ns more per checked +offset. This is an upper bound for the check, since it is written in source +and not emitted inline. + +Code-point indexing on wasm is O(n) per index (walk from the start) unless +the runtime keeps an index beside each string. I did not measure it at size: +core wasm starts its heap at 1024, below string literals laid out from 2048, +so a program that allocates more than about 1 KiB overwrites its own literals +(recorded in `docs/UNICODE-STRINGS.adoc`, "Findings"). A string built by +doubling failed with `Out of bounds memory access` at every size I tried. + +== Options + +=== A. Octets everywhere; fail loudly off a character boundary + +The Rust model. `len` and `string_length` count UTF-8 octets on every +backend. `string_sub(s, start, n)` and `string_get(s, i)` stop with a named +error when an offset is inside a character. `string_char_code_at(s, i)` stays +the raw octet read and never fails in range. A `String` is then always a +sequence of Unicode scalar values. + +Migration cost:: +* Interpreter and wasm: no change of meaning. The new failure reaches the 4 + per-unit slice sites over arbitrary text, which must move to code-point + iteration (#829's `code_points`), and the 11 `string_get` sites, of which + the byte-oriented ones (5 in `SafeHex`, 1 in `json`) and the 4 ASCII + comparisons in `io.affine` should move to `string_char_code_at`. +* Bun-ESM: every string site changes meaning for non-ASCII data and none for + ASCII data. base64, hex and JSON escaping become correct. No tracked test + indexes non-ASCII text, so no existing expectation changes; #829's + `test_unicode_octets` pins the present divergence and would be updated. +* Satellites: nothing. All 48 of their sites are array lengths. +Bun cost:: A-cache above. Scans cost about 2 times today's at size. `len` +becomes O(n) on first use of a string; an accumulator loop that calls `len` +each turn must be rewritten to count. +`Char`:: becomes a Unicode scalar value. `string_get` at a boundary returns +the scalar that starts there. `LitChar of char` becomes an `Int`-carrying +constructor and the lexer accepts `'é'`. This is a separate change touching +the type checker and every backend, so it would be its own ADR step. +wasm cost:: one load and compare per checked offset (measured above). +Proof-friendliness:: best of the options. A string is a `list byte` with a +well-formedness predicate; `len` is `List.length`; `++` is append, so +`len (a ++ b) = len a + len b`; a cut at a boundary preserves +well-formedness. The DEED 998-octet bound is stated in the same measure the +printer indexes by, so the proof needs one measure. It also matches the +linear-memory model the K-1 proof in `formal/` already uses. + +=== B. Code points everywhere + +`len` counts Unicode scalar values; indices are code-point positions. +`string_sub` cannot cut a character. + +Migration cost:: +* Interpreter and wasm change meaning for non-ASCII data at all 29 + 11 + 23 + + 6 stdlib string sites. +* Byte-oriented code breaks: base64 over code points is not base64. The 6 + `string_char_code_at` sites in `encoding.affine` and the 5 `string_get` + sites in `SafeHex` need a new byte API first. +Bun cost:: B-cache above: similar to A-cache on scans, 18 times dearer to +build the view, and the worst W4 result measured. +`Char`:: a scalar value, as in A. +wasm cost:: O(n) per index, or an index structure beside every string. +Proof-friendliness:: workable but weaker for the DEED bound. The printer +would index by code point and budget by octet, so every lemma has to relate +two measures through the per-character width. + +=== C. Keep the per-backend meaning; document it; deprecate `len` on strings + +Migration cost:: no site changes meaning. The 48 string `len` sites (29 in +the stdlib) get a deprecation warning, so the stdlib must migrate anyway. +Bun cost:: none. +`Char`:: stays one octet on octet backends. +wasm cost:: none. +Proof-friendliness:: poor. A program's meaning stays a function of the +backend, so a proof about source says nothing about the Bun artefact. The +DEED printer is compiled to Bun-ESM. + +The base64 and hex results stay silently wrong on Bun until each caller +migrates. + +=== D. `String` as a `Uint8Array` of UTF-8 on Bun (#831 option 3) + +One representation on every backend; A's semantics with no cache. + +Migration cost:: as A in AffineScript source. In the compiler, every string +operation in `lib/codegen_deno.ml` and every host binding changes; 227 +`extern fn` signatures carry a `String`. +Bun cost:: E-bytes above. `len` and index are as fast as today. `++` copies, +so string building is 16 to 85 times slower in the measured loops, and each +host call decodes. +`Char`, wasm cost, proof-friendliness:: as A. The proof story is marginally +better than A, because the Bun artefact holds the same bytes the proof talks +about, with no cache to trust. + +=== E. Unconventional: no `Int` index into text at all + +Split the two uses that the evidence shows are already distinct. + +* `Bytes` for byte-oriented code (base64, hex, digests): O(1) octet length + and index on every backend. `utf8_encode : String -> Bytes` and + `utf8_decode : Bytes -> Result[String, ...]`. `stdlib/Deno.affine` already + has an opaque `Bytes` and `Crypto.affine` uses `[Int]`; this would unify + them. +* `String` for text, with no integer indexing. Positions are an opaque + `Utf8Offset`, produced only by `find`, by iteration, or by a checked + conversion from `Int`. `string_sub` takes offsets, so it cannot be handed + a position inside a character, and mixing octet counts with code-point + counts is a type error and not a run-time value. + +This takes #831's option 2 (an opaque offset type) one step further by +removing the `Int` entry point from text altogether. + +Migration cost:: the highest. All 48 string `len` sites, 11 `string_get`, +23 `string_sub` and 6 `string_char_code_at` sites in the stdlib are +rewritten, and two types are added to the checker and every backend. +Bun cost:: `Bytes` is a `Uint8Array` used only where bytes are wanted, so +text keeps JS string concatenation. Offsets can carry both the octet and the +UTF-16 position, which removes the cache. +`Char`:: a scalar value; bytes are `Int` in 0..255. +wasm cost:: as A. +Proof-friendliness:: best in the long run. "An offset is on a boundary" is an +invariant of the type, established once where offsets are made, and not a +side condition on every `string_sub` call. + +== Ratings + +1 is worst, 5 is best. "Elegance / correctness" is how well the option fits +the problem and whether programs mean one thing. "Dependability / security" +is how it fails, what it costs to keep right, and what it does to +byte-exact code such as encodings and digests. + +[cols="3,1,1,4",options="header"] +|=== +| Option | Elegance / correctness | Dependability / security | Other aspects + +| A. Octets, loud off-boundary +| 4 +| 4 +| Performance: `len` on Bun becomes O(n) on first use. Proof: one measure. Estate: matches the DEED octet bound directly. + +| B. Code points +| 3 +| 3 +| Ergonomics: closest to what a user means by "length", but a code point is still not a user-perceived character. Performance: needs an index structure on wasm. + +| C. Keep, document, deprecate +| 1 +| 2 +| Cheapest today. Leaves base64 and hex wrong on Bun for non-ASCII input, with no failure. + +| D. `Uint8Array` representation +| 3 +| 3 +| Performance: string building and host calls pay. Interop: 227 extern signatures. Removes the cache A needs. + +| E. `Bytes` + opaque offsets +| 5 +| 5 +| Cost: largest migration and two new types. Best taken after A, which it does not contradict. +|=== + +== Recommendation + +*Option A*, with the Bun lowering measured as A-cache plus +`Buffer.byteLength` for `len`, and *Option E recorded as the direction of +travel*. + +* A makes the three backends agree, makes the byte-oriented stdlib correct on + Bun, and gives the DEED proof one measure. Its migration is small in this + repository: no satellite changes, 4 slice sites and 11 `string_get` sites + in the stdlib, and no existing test expectation changes. +* Its cost is real and bounded: about 2 times on scan loops at size, and + `len` no longer O(1) on Bun. +* E is the more final answer, since it turns the unit confusion into a type + error. A's offsets are exactly the values an `Utf8Offset` would wrap, so A + is a step towards E and not a detour. +* `Char` as a scalar value follows from A but is a separate change. + +I would not choose D: it buys a slightly cleaner proof story at a measured 16 +to 85 times cost on string building. + +=== If A is accepted: suggested order + +. Add the boundary-checked operations under new names beside the old ones, + with tests on all backends, and migrate the stdlib sites listed above. +. Switch `len`, `string_get` and `string_sub` on Bun-ESM to the octet + lowering; update `docs/UNICODE-STRINGS.adoc` and the #829 test that pins + the divergence. +. Turn the off-boundary failure on for the interpreter and wasm. +. Separate ADR: `Char` as a scalar value. + +Before step 2, repeat the benchmark on the real workload: the DEED printer +compiled to Bun-ESM, timed before and after. + +=== Beyond this repository + +This decision reaches any estate code compiled to Bun-ESM that indexes +strings, the DEED printer and kyX in particular. Those repositories should be +searched for the seven builtins before step 2, and the result kept with the +estate's list of cross-repository migrations. + +[#reproduce] +== Reproducing the measurements + +Usage counts (run at the repository root): + +[source,sh] +---- +cnt() { git ls-files $2 | grep '\.affine$' | xargs -r grep -hvE '^\s*//' \ + | grep -oE "(^|[^A-Za-z0-9_.])$1\(" | wc -l; } +for f in len string_length string_get string_sub string_char_code_at char_to_int string_find; do + echo "$f stdlib=$(cnt $f stdlib) satellites=$(cnt $f 'affinescript-cadre affinescript-crdt affinescript-deno-test affinescript-dom affinescript-router affinescript-tea affinescript-vite') tests=$(cnt $f 'tests test')" +done + +# every `len` site, for the string/array classification (read by hand) +git ls-files '*.affine' | xargs grep -nE "(^|[^A-Za-z0-9_.])len\(" + +# non-ASCII inside a string or char literal +git ls-files '*.affine' | xargs grep -nP '^(?!\s*//).*["\x27][^"\x27\n]*[^\x00-\x7F][^"\x27\n]*["\x27]' + +# the per-unit slice idiom +git ls-files stdlib | xargs grep -nE "string_sub\([^;]*, *1\)" + +# extern signatures that carry a String +git ls-files '*.affine' | xargs grep -hE '^\s*(pub )?extern fn' | grep -c String +---- + +base64 on core wasm and on Bun-ESM: + +[source,sh] +---- +( grep -v '^module\|^use ' stdlib/encoding.affine + printf 'pub fn main() -> Int {\n println("b64(é)=" ++ to_base64("é"));\n println("b64(🦜)=" ++ to_base64("🦜"));\n 0\n}\n' ) > /tmp/enc_inline.affine +affinescript compile /tmp/enc_inline.affine -o /tmp/enc_inline.wasm && bun run /tmp/enc_inline.wasm +affinescript compile /tmp/enc_inline.affine -o /tmp/enc_inline.bun.js --bun-esm \ + && bun -e 'const m = await import("/tmp/enc_inline.bun.js"); m.main()' +---- + +wasm boundary-check cost. Save as `scan.affine`, replace `BODY` with each of +the three bodies, compile to `.wasm` and time `bun run`: + +[source] +---- +fn scan(s: String, n: Int) -> Int { + let mut a = 0; + let mut i = 0; + while i < n { BODY i = i + 1; } + a +} +pub fn main() -> Int { + let s = "<`aé漢🦜 naïve ` repeated 12 times>"; + let n = len(s); + let mut r = 0; + let mut t = 0; + while r < 200000 { t = t + scan(s, n); r = r + 1; } + println(int_to_string(t)); + 0 +} +---- + +. `a = a + 1;` +. `a = a + string_char_code_at(s, i);` +. `let b = string_char_code_at(s, i); if (b & 192) != 128 { a = a + b; }` + +[#bench] +== Appendix: the Bun benchmark + +This is a measurement script, kept here as a listing so that the numbers can +be reproduced. It is not part of the compiler or its runtime and is not +tracked as a source file. Save it as `strbench.mjs` and run `bun strbench.mjs`. + +[source,javascript] +---- +// Throwaway measurement for ADR-028 (#831). Candidate lowerings of string +// length / index / slice on Bun. Not shipped; not part of the compiler. +const enc = new TextEncoder(), dec = new TextDecoder("utf-8", { fatal: true }); + +// ---- candidates ------------------------------------------------------------ +// U16: today's Bun-ESM lowering (UTF-16 code units). +const u16 = { + len: (s) => s.length, + at: (s, i) => s.charCodeAt(i), + sub: (s, i, n) => s.slice(i, i + n), +}; +// A-naive: octets, re-encode on every call. +const aNaive = { + len: (s) => enc.encode(s).length, + at: (s, i) => enc.encode(s)[i], + sub: (s, i, n) => { const b = enc.encode(s); chk(b, i); chk(b, i + n); return dec.decode(b.subarray(i, i + n)); }, +}; +function chk(b, i) { if (i < b.length && (b[i] & 0xC0) === 0x80) throw new Error("string_sub: offset " + i + " is inside a character"); } +// A-cache: octets through a one-entry cache of the last string's UTF-8 view, +// with an all-ASCII fast path (octet index == UTF-16 index). +let cS = null, cB = null, cAscii = false; +function view(s) { + if (s !== cS) { cB = enc.encode(s); cS = s; cAscii = cB.length === s.length; } + return cB; +} +const aCache = { + len: (s) => view(s).length, + at: (s, i) => { const b = view(s); return cAscii ? s.charCodeAt(i) : b[i]; }, + sub: (s, i, n) => { + const b = view(s); + if (cAscii) return s.slice(i, i + n); + chk(b, i); chk(b, i + n); + return dec.decode(b.subarray(i, i + n)); + }, +}; +// A-len-only fast length: Buffer.byteLength (no allocation). +const aByteLen = { len: (s) => Buffer.byteLength(s, "utf8") }; +// B-naive: code points, walk from the start on every call. +const bNaive = { + len: (s) => { let n = 0; for (const _ of s) n++; return n; }, + at: (s, i) => { let k = 0; for (const c of s) { if (k++ === i) return c.codePointAt(0); } return -1; }, + sub: (s, i, n) => { let k = 0, o = ""; for (const c of s) { if (k >= i && k < i + n) o += c; k++; } return o; }, +}; +// B-cache: code points through a one-entry cache of the code-point array. +let pS = null, pA = null; +function cps(s) { if (s !== pS) { pA = Array.from(s); pS = s; } return pA; } +const bCache = { + len: (s) => cps(s).length, + at: (s, i) => cps(s)[i].codePointAt(0), + sub: (s, i, n) => cps(s).slice(i, i + n).join(""), +}; +// E: String is a Uint8Array of UTF-8 (issue #831 option 3). +const eBytes = { + len: (b) => b.length, + at: (b, i) => b[i], + sub: (b, i, n) => { chk(b, i); chk(b, i + n); return b.subarray(i, i + n); }, + cat: (a, b) => { const o = new Uint8Array(a.length + b.length); o.set(a, 0); o.set(b, a.length); return o; }, +}; + +// ---- inputs ---------------------------------------------------------------- +const rep = (u, n) => u.repeat(n); +const inputs = { + "ascii-1k": rep("the quick brown fox ", 50), + "ascii-100k": rep("the quick brown fox ", 5000), + "mixed-1k": rep("aé漢🦜 naïve ", 60), + "mixed-100k": rep("aé漢🦜 naïve ", 6000), +}; + +// ---- harness --------------------------------------------------------------- +function time(f, budgetMs = 300) { + f(); f(); + let runs = 0; const t0 = performance.now(); let t = t0; + while (t - t0 < budgetMs && runs < 1e6) { f(); runs++; t = performance.now(); } + return (t - t0) / runs; // ms per run +} +const fmt = (ms) => ms >= 1 ? ms.toFixed(2) + " ms" : ms >= 0.001 ? (ms * 1e3).toFixed(2) + " us" : (ms * 1e6).toFixed(0) + " ns"; +let sink = 0; +const rows = []; +function row(work, input, cand, ms) { rows.push({ work, input, cand, t: fmt(ms) }); } + +for (const [name, s] of Object.entries(inputs)) { + const bytes = enc.encode(s); + // W1: one len() call on a string the cache has not seen: a pool of distinct + // strings of the same size, visited in turn, so every call is a cache miss. + const pool = []; const poolN = s.length > 10000 ? 32 : 512; + for (let k = 0; k < poolN; k++) pool.push((s.slice(0, s.length - 6) + String(100000 + k)).normalize()); + for (const p of pool) p.charCodeAt(0); + let pk = 0; + for (const [cn, c] of [["U16", u16], ["A-naive", aNaive], ["A-cache", aCache], ["A-byteLength", aByteLen], ["B-naive", bNaive], ["B-cache", bCache]]) + row("W1 len, cache miss", name, cn, time(() => { sink += c.len(pool[pk++ % poolN]); })); + row("W1 len, cache miss", name, "E-bytes", time(() => { sink += eBytes.len(bytes); })); + row("W1b len, same string again", name, "A-cache", time(() => { sink += aCache.len(s); })); + row("W1b len, same string again", name, "B-cache", time(() => { sink += bCache.len(s); })); + + // W2: the stdlib scan idiom: n = len(s); for i in 0..n { string_char_code_at(s, i) } + const scan = (c, x) => () => { const n = c.len(x); let a = 0; for (let i = 0; i < n; i++) a += c.at(x, i); sink += a; }; + for (const [cn, c] of [["U16", u16], ["A-cache", aCache], ["B-cache", bCache]]) row("W2 scan", name, cn, time(scan(c, s))); + row("W2 scan", name, "E-bytes", time(scan(eBytes, bytes))); + if (name.endsWith("1k")) for (const [cn, c] of [["A-naive", aNaive], ["B-naive", bNaive]]) row("W2 scan", name, cn, time(scan(c, s))); + + // W3: the per-unit slice idiom: out = out ++ string_sub(s, i, 1) at every boundary. + if (name.endsWith("1k")) { + const offs8 = [], offs16 = [], offsCp = []; + { let o8 = 0, o16 = 0, k = 0; for (const ch of s) { offs8.push([o8, enc.encode(ch).length]); offs16.push([o16, ch.length]); offsCp.push([k, 1]); o8 += enc.encode(ch).length; o16 += ch.length; k++; } } + const rebuild = (c, x, offs) => () => { let o = ""; for (const [i, n] of offs) o += c.sub(x, i, n); sink += o.length; }; + row("W3 slice+concat", name, "U16", time(rebuild(u16, s, offs16))); + row("W3 slice+concat", name, "A-cache", time(rebuild(aCache, s, offs8))); + row("W3 slice+concat", name, "A-naive", time(rebuild(aNaive, s, offs8))); + row("W3 slice+concat", name, "B-cache", time(rebuild(bCache, s, offsCp))); + row("W3 slice+concat", name, "B-naive", time(rebuild(bNaive, s, offsCp))); + row("W3 slice+concat", name, "E-bytes", time(() => { let o = new Uint8Array(0); for (const [i, n] of offs8) o = eBytes.cat(o, eBytes.sub(bytes, i, n)); sink += o.length; })); + } + // W4: build a string by repeated append, then take len after every append + // (accumulator pattern; defeats a one-entry cache, the worst case for A-cache). + if (name.endsWith("1k")) { + const piece = s.slice(0, 20), pieceB = enc.encode(piece); + const acc = (c) => () => { let o = "", t = 0; for (let k = 0; k < 200; k++) { o += piece; t += c.len(o); } sink += t; }; + for (const [cn, c] of [["U16", u16], ["A-cache", aCache], ["A-byteLength", aByteLen], ["B-cache", bCache]]) row("W4 append+len x200", name, cn, time(acc(c))); + row("W4 append+len x200", name, "E-bytes", time(() => { let o = new Uint8Array(0), t = 0; for (let k = 0; k < 200; k++) { o = eBytes.cat(o, pieceB); t += o.length; } sink += t; })); + } +} +// W5: host boundary cost for E: decode on every println / JS interop call. +for (const [name, s] of Object.entries(inputs)) { + const bytes = enc.encode(s); + row("W5 host boundary (decode)", name, "E-bytes", time(() => { sink += dec.decode(bytes).length; })); + row("W5 host boundary (decode)", name, "U16/A/B", time(() => { sink += s.length; })); +} +console.log("bun " + Bun.version + " " + process.platform + "/" + process.arch); +let last = ""; +for (const r of rows) { const k = r.work + " | " + r.input; if (k !== last) { console.log("\n" + k); last = k; } console.log(" " + r.cand.padEnd(14) + r.t.padStart(12)); } +if (sink === -1) console.log(sink); +----