Skip to content

perf(c): borrow shared tails in String.drop - #2131

Closed
sebastianbreguel wants to merge 1 commit into
bendlang:mainfrom
sebastianbreguel:perf/c-string-drop
Closed

sebastianbreguel wants to merge 1 commit into
bendlang:mainfrom
sebastianbreguel:perf/c-string-drop

Conversation

@sebastianbreguel

Copy link
Copy Markdown
Contributor

String.drop now consumes unique cells as before and borrows the suffix once it reaches a shared cell. The C walker retains the selected tail before releasing its shared root. This avoids taking and releasing every skipped shared cell.

Base's definition, checker reduction and the JS backend are unchanged. The JS emitted for all 21 benchmark programs is byte-identical between base and branch.

Results

The Map.get workload adapts #2074: 4096 entries, keys with P copies of 'a' followed by four suffix letters, then 50,000 lookups. These are whole-process medians, including map construction, query creation, lookups and cleanup, against f311527. The tested branch is b5ca688.

Added prefix P macOS arm64, base → branch Docker Linux arm64, base → branch
0 chars 12.0 → 11.0 ms (-8%) 18.95 → 16.30 ms (-14%)
16 chars 24.8 → 20.7 ms (-17%) 39.4 → 29.8 ms (-24%)
64 chars 61.5 → 46.9 ms (-24%) 101.75 → 71.20 ms (-30%)
256 chars 204.85 → 137.40 ms (-33%) 334.8 → 219.5 ms (-34%)

All 20 pairs improve in each Map.get row above. Peak RSS is unchanged at the displayed precision for those rows. This is a time improvement, not a memory-reduction claim.

There are 21 cases per OS, each with 20 interleaved pairs: 1680 timed child processes in total. Pair order alternates; each side has two warm-ups, and every measured child is a fresh process. Each sample must print the independently expected checksum and exit successfully. An intentional wrong checksum makes the sampler reject the run.

The controls cover 16, 1024, 65,536, 1,048,576 and 8,388,608 characters, unique and retained/shared inputs, zero and overlong drops, and a 64 KiB private prefix over a retained 1 MiB tail, stopped before and after the handoff. Map.get also has a P64 miss case. Prefix lengths vary at a fixed 4096 entries; this is not entry-count scaling.

Dropping half an 8 Mi-character retained input, then counting the returned tail, takes 137.25 → 122.9 ms on macOS and 220.15 → 194.0 ms on Linux, including setup and the original-input check. The unique control is almost flat: 84.3 → 83.75 ms on macOS, 135.05 → 135.5 ms on Linux.

Small costs remain visible in the full tables:

  • Linux unique 8 Mi-character half-drop: +0.45 ms / +0.33%, slower in 14/20 pairs.
  • Linux unique 1 Mi-character overlong drop: +0.25 ms / +1.57%, slower in 15/20 pairs.
  • Linux private-prefix/before-handoff control: inner median 10 → 11 ms; whole process 30.95 → 31.0 ms. IO.now has 1 ms resolution.
  • Linux 1 Ki-character controls: +0.05–0.1 ms in process medians, dominated by startup; their median paired differences are zero.
  • The largest median RSS increase is 0.4 MiB, below 1%. There is no claim of zero cost in every control.

The direct-control inner interval includes String.drop, String.length of its result and consumer cleanup. It is not isolated drop latency. Building the input occurs before the inner timestamp. A retained input is checked again after that interval; this check is inside whole-process time. The 16-character rows are startup/timer-resolution controls.

Why this helps

In a separate instrumented P64 run, String.drop is called 703,167 times: 553,167 calls drop zero characters, and 3,350,000 skipped cells use the borrowed path. That instrumented binary is excluded from timing data. CPU sampling of a longer, 500,000-query P256 variant attributes the old drop cost to span_fade/term_drop; String.eq remains a large cost after the change. Query generation and map construction also remain, so this does not remove all lookup work.

The unique/refcount-one path still uses ctr_take and spare_free. Borrowed descendants are sealed or static, and the root stays alive until the result is retained. A fresh unique prefix can transition to the shared path partway through. term_triv is checked before reading a refcount.

Tests

VERIFIED for the native CPU cases measured above.

  • 10 fixtures on base and branch × C/Bun/Node/interpreter × macOS/Linux: 160 checks, all expected output lines matched. These include the existing string, suffix and map-cursor tests and the new native-drop fixture.
  • Both OSes: existing string kit and new fixture on both sides with BEND_POISON and AddressSanitizer/UndefinedBehaviorSanitizer. All passed, with leak detection disabled. Linux sanitizer libraries were added to a separate test-only image; timing used the unchanged image below.
  • Both sides on real Metal: the new fixture passes with --gpu on. It checks a shared string across 16 parallel lanes. This is behavior coverage, not a GPU timing claim.
  • Dynamic full-U32 Char, NUL, surrogate and astral values; empty, zero, exact, overlong and huge-count drops; preserved original values, unique inputs and unique-prefix/shared-tail inputs. Independent probes also covered RFC1, partial application and a first-class String.drop reference.
  • Repo gate: 56/56. comp.ts: 65,999 / 66,000 ttok. The cap is unchanged. git diff --check passes.
  • Typecheck is not green: strict TypeScript 7.0.2 reports the same 16 diagnostics (27 lines, after line-number normalization) on base and branch, including missing Node type declarations and existing term-type errors. No new diagnostic was added. No standalone lint command is configured here.
  • The full mini-cluster/perf gates and CUDA were not run locally.

Review guide

Start at str_drop in bend2/comp.ts, then its String.drop entry in OPERATIONS and tests/run/string_drop_native.bend. The remaining diff shortens existing ownership/emitter comments to fit the permanent source cap; it changes no compiler behavior. The public String.drop signature and representation stay the same. Revert the intrinsic entry and helper to restore the prior native path.

Environment

macOS 26.5.1, Apple M4 Pro, 24 GiB RAM, Apple clang 21.0.0; Bun 1.4.2, Node 25.9.0, uv 0.13.7, Python sampler 3.14.5. C flags: -O3 -g -std=c11, linked with -lpthread -lm.

Linux arm64 is a Debian 13.7 VM on the same Apple Silicon Mac, not bare-metal Linux. Container limits: 4 CPUs, 8 GiB RAM, 8 GiB memory+swap (no extra swap). Debian clang 19.1.7, Bun 1.4.2, Node 25.9.0, uv 0.13.7, Python 3.12.16. The timed image ID was sha256:99df25fd443929b4bf3095c2dc763fde6c29cbe7bb2d458d79ec6e50523eced8. No other build ran alongside a timing batch. The benchmarks have no bang or GPU work. RSS is the child process high-water mark, not attributed allocations or GPU memory.

All measurements: p50 / p80 / p95, 20 samples per side

macOS arm64

Case Metric Base p50 / p80 / p95 Branch p50 / p80 / p95 p50 change
get-0 wall (ms) 12.0 / 12.1 / 12.3 11.0 / 11.2 / 11.2 -8.3%
get-0 inner (ms) 10.0 / 10.0 / 10.0 9.00 / 9.00 / 9.00 -10.0%
get-0 RSS (MiB) 2.10 / 2.10 / 2.10 2.10 / 2.10 / 2.10 0.0%
get-16 wall (ms) 24.8 / 24.9 / 25.2 20.7 / 21.0 / 21.7 -16.5%
get-16 inner (ms) 20.0 / 21.0 / 21.0 16.0 / 16.2 / 17.0 -20.0%
get-16 RSS (MiB) 3.60 / 3.60 / 3.60 3.60 / 3.60 / 3.60 0.0%
get-64 wall (ms) 61.5 / 62.2 / 62.8 46.9 / 47.8 / 48.2 -23.7%
get-64 inner (ms) 50.0 / 51.0 / 51.0 36.0 / 36.2 / 37.0 -28.0%
get-64 RSS (MiB) 8.10 / 8.10 / 8.10 8.10 / 8.10 / 8.10 0.0%
get-64-miss wall (ms) 62.4 / 62.8 / 63.1 46.2 / 46.6 / 46.9 -26.0%
get-64-miss inner (ms) 51.0 / 51.0 / 52.0 35.0 / 35.0 / 36.0 -31.4%
get-64-miss RSS (MiB) 8.10 / 8.10 / 8.10 8.10 / 8.10 / 8.10 0.0%
get-256 wall (ms) 205 / 208 / 224 137 / 139 / 140 -32.9%
get-256 inner (ms) 177 / 178 / 189 109 / 110 / 112 -38.2%
get-256 RSS (MiB) 26.1 / 26.1 / 26.1 26.1 / 26.1 / 26.1 0.0%
drop-16-unique-half wall (ms) 1.70 / 1.80 / 1.91 1.70 / 1.82 / 1.91 0.0%
drop-16-unique-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-16-unique-half RSS (MiB) 1.50 / 1.50 / 1.50 1.50 / 1.50 / 1.50 0.0%
drop-16-shared-half wall (ms) 1.70 / 1.80 / 1.91 1.70 / 1.80 / 1.91 0.0%
drop-16-shared-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-16-shared-half RSS (MiB) 1.50 / 1.50 / 1.50 1.50 / 1.50 / 1.50 0.0%
drop-1024-unique-half wall (ms) 1.70 / 1.80 / 1.91 1.70 / 1.80 / 2.00 0.0%
drop-1024-unique-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-1024-unique-half RSS (MiB) 1.50 / 1.50 / 1.50 1.50 / 1.50 / 1.50 0.0%
drop-1024-shared-half wall (ms) 1.70 / 1.90 / 1.91 1.70 / 1.84 / 2.10 0.0%
drop-1024-shared-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-1024-shared-half RSS (MiB) 1.50 / 1.50 / 1.50 1.50 / 1.50 / 1.50 0.0%
drop-65536-unique-half wall (ms) 2.50 / 2.52 / 2.61 2.40 / 2.60 / 2.70 -4.0%
drop-65536-unique-half inner (ms) 0 / 0.200 / 1.00 0 / 0 / 0.050 n/a
drop-65536-unique-half RSS (MiB) 4.10 / 4.10 / 4.10 4.10 / 4.10 / 4.10 0.0%
drop-65536-shared-half wall (ms) 2.70 / 2.80 / 2.82 2.60 / 2.80 / 2.91 -3.7%
drop-65536-shared-half inner (ms) 0 / 1.00 / 1.00 0 / 1.00 / 1.00 n/a
drop-65536-shared-half RSS (MiB) 4.10 / 4.10 / 4.10 4.10 / 4.10 / 4.10 0.0%
drop-1048576-unique-half wall (ms) 11.8 / 12.0 / 12.2 11.7 / 12.0 / 12.2 -0.4%
drop-1048576-unique-half inner (ms) 3.00 / 3.00 / 3.05 3.00 / 3.00 / 3.00 0.0%
drop-1048576-unique-half RSS (MiB) 41.6 / 41.6 / 41.6 41.6 / 41.6 / 41.6 0.0%
drop-1048576-shared-half wall (ms) 18.4 / 18.6 / 19.0 16.5 / 16.7 / 17.0 -10.3%
drop-1048576-shared-half inner (ms) 6.00 / 7.00 / 7.00 4.00 / 5.00 / 5.00 -33.3%
drop-1048576-shared-half RSS (MiB) 41.5 / 41.5 / 41.5 41.6 / 41.6 / 41.6 0.2%
drop-8388608-unique-half wall (ms) 84.3 / 86.2 / 89.4 83.8 / 84.8 / 85.4 -0.7%
drop-8388608-unique-half inner (ms) 27.0 / 27.2 / 32.1 26.0 / 26.2 / 27.0 -3.7%
drop-8388608-unique-half RSS (MiB) 322 / 322 / 322 322 / 322 / 322 0.0%
drop-8388608-shared-half wall (ms) 137 / 139 / 144 123 / 124 / 125 -10.5%
drop-8388608-shared-half inner (ms) 54.0 / 54.2 / 56.2 39.0 / 40.0 / 40.0 -27.8%
drop-8388608-shared-half RSS (MiB) 322 / 322 / 322 322 / 322 / 322 0.0%
drop-1048576-unique-zero wall (ms) 12.0 / 12.2 / 12.3 11.9 / 12.1 / 12.3 -0.8%
drop-1048576-unique-zero inner (ms) 3.00 / 4.00 / 4.00 3.00 / 3.00 / 4.00 0.0%
drop-1048576-unique-zero RSS (MiB) 41.6 / 41.6 / 41.6 41.6 / 41.6 / 41.6 0.0%
drop-1048576-unique-over wall (ms) 11.7 / 11.9 / 12.0 11.5 / 11.7 / 12.0 -2.1%
drop-1048576-unique-over inner (ms) 3.00 / 3.00 / 3.05 3.00 / 3.00 / 3.00 0.0%
drop-1048576-unique-over RSS (MiB) 41.5 / 41.5 / 41.5 41.6 / 41.6 / 41.6 0.2%
drop-1048576-shared-zero wall (ms) 18.6 / 18.7 / 18.7 18.6 / 18.9 / 19.1 0.3%
drop-1048576-shared-zero inner (ms) 6.00 / 7.00 / 7.00 6.00 / 7.00 / 7.00 0.0%
drop-1048576-shared-zero RSS (MiB) 41.6 / 41.6 / 41.6 41.5 / 41.5 / 41.5 -0.2%
drop-1048576-shared-over wall (ms) 18.5 / 18.6 / 18.7 14.7 / 14.8 / 14.9 -20.5%
drop-1048576-shared-over inner (ms) 7.00 / 7.00 / 7.00 3.00 / 3.00 / 3.05 -57.1%
drop-1048576-shared-over RSS (MiB) 41.6 / 41.6 / 41.6 41.5 / 41.5 / 41.5 -0.2%
drop-1048576-prefix-before wall (ms) 19.3 / 19.6 / 20.1 19.2 / 19.4 / 19.6 -0.8%
drop-1048576-prefix-before inner (ms) 7.00 / 7.00 / 7.00 7.00 / 7.00 / 7.05 0.0%
drop-1048576-prefix-before RSS (MiB) 43.0 / 43.0 / 43.0 43.0 / 43.0 / 43.0 0.0%
drop-1048576-prefix-after wall (ms) 19.5 / 19.8 / 20.0 19.4 / 19.7 / 19.8 -0.5%
drop-1048576-prefix-after inner (ms) 7.00 / 7.00 / 7.00 7.00 / 7.00 / 7.05 0.0%
drop-1048576-prefix-after RSS (MiB) 43.1 / 43.1 / 43.1 43.1 / 43.1 / 43.1 0.0%

Docker Linux arm64

Case Metric Base p50 / p80 / p95 Branch p50 / p80 / p95 p50 change
get-0 wall (ms) 19.0 / 19.1 / 19.4 16.3 / 16.4 / 16.5 -14.0%
get-0 inner (ms) 17.0 / 18.0 / 18.0 15.0 / 15.0 / 15.0 -11.8%
get-0 RSS (MiB) 16.9 / 16.9 / 16.9 16.9 / 16.9 / 16.9 0.0%
get-16 wall (ms) 39.4 / 40.0 / 40.2 29.8 / 30.4 / 30.8 -24.4%
get-16 inner (ms) 36.0 / 36.0 / 36.1 26.0 / 26.0 / 27.1 -27.8%
get-16 RSS (MiB) 16.9 / 16.9 / 16.9 16.9 / 16.9 / 16.9 0.0%
get-64 wall (ms) 102 / 106 / 114 71.2 / 76.1 / 78.0 -30.0%
get-64 inner (ms) 89.5 / 93.0 / 101 59.0 / 63.2 / 65.2 -34.1%
get-64 RSS (MiB) 16.9 / 17.0 / 17.0 16.9 / 17.0 / 17.0 0.0%
get-64-miss wall (ms) 100 / 101 / 103 72.9 / 73.6 / 74.2 -27.2%
get-64-miss inner (ms) 88.0 / 89.0 / 90.0 61.0 / 61.0 / 62.1 -30.7%
get-64-miss RSS (MiB) 16.9 / 16.9 / 16.9 16.9 / 16.9 / 16.9 0.0%
get-256 wall (ms) 335 / 340 / 346 220 / 229 / 237 -34.4%
get-256 inner (ms) 302 / 309 / 313 188 / 198 / 206 -37.6%
get-256 RSS (MiB) 33.6 / 33.6 / 33.6 33.6 / 33.6 / 33.6 0.0%
drop-16-unique-half wall (ms) 0.500 / 0.600 / 0.705 0.500 / 0.640 / 0.800 0.0%
drop-16-unique-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-16-unique-half RSS (MiB) 16.8 / 16.8 / 16.8 16.8 / 16.8 / 16.8 0.0%
drop-16-shared-half wall (ms) 0.550 / 0.620 / 0.805 0.500 / 0.600 / 0.710 -9.1%
drop-16-shared-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-16-shared-half RSS (MiB) 16.9 / 16.9 / 16.9 16.9 / 16.9 / 16.9 0.0%
drop-1024-unique-half wall (ms) 0.500 / 0.600 / 0.605 0.550 / 0.800 / 0.805 10.0%
drop-1024-unique-half inner (ms) 0 / 0 / 0 0 / 0 / 0.050 n/a
drop-1024-unique-half RSS (MiB) 16.7 / 16.7 / 16.7 16.7 / 16.7 / 16.7 0.0%
drop-1024-shared-half wall (ms) 0.500 / 0.600 / 0.805 0.600 / 0.600 / 0.710 20.0%
drop-1024-shared-half inner (ms) 0 / 0 / 0 0 / 0 / 0 n/a
drop-1024-shared-half RSS (MiB) 16.9 / 16.9 / 16.9 16.9 / 16.9 / 16.9 0.0%
drop-65536-unique-half wall (ms) 1.55 / 1.60 / 1.71 1.60 / 1.72 / 1.81 3.2%
drop-65536-unique-half inner (ms) 0.500 / 1.00 / 1.00 0 / 1.00 / 1.00 -100.0%
drop-65536-unique-half RSS (MiB) 16.7 / 16.7 / 16.7 16.7 / 16.7 / 16.7 0.0%
drop-65536-shared-half wall (ms) 2.15 / 2.20 / 2.20 2.00 / 2.12 / 2.31 -7.0%
drop-65536-shared-half inner (ms) 1.00 / 1.00 / 1.00 0 / 1.00 / 1.00 -100.0%
drop-65536-shared-half RSS (MiB) 16.8 / 16.8 / 16.8 16.8 / 16.8 / 16.8 0.0%
drop-1048576-unique-half wall (ms) 16.5 / 16.7 / 17.2 16.6 / 16.8 / 16.8 0.6%
drop-1048576-unique-half inner (ms) 6.00 / 7.00 / 7.00 6.00 / 7.00 / 7.00 0.0%
drop-1048576-unique-half RSS (MiB) 50.6 / 51.0 / 51.4 50.5 / 51.0 / 51.3 -0.1%
drop-1048576-shared-half wall (ms) 28.0 / 28.6 / 29.2 24.6 / 25.4 / 26.0 -12.1%
drop-1048576-shared-half inner (ms) 10.0 / 10.0 / 10.0 7.00 / 7.00 / 7.00 -30.0%
drop-1048576-shared-half RSS (MiB) 50.4 / 50.8 / 51.3 50.2 / 50.8 / 51.0 -0.3%
drop-8388608-unique-half wall (ms) 135 / 139 / 145 135 / 141 / 144 0.3%
drop-8388608-unique-half inner (ms) 53.0 / 56.0 / 58.1 53.0 / 56.0 / 57.1 0.0%
drop-8388608-unique-half RSS (MiB) 330 / 331 / 331 330 / 331 / 331 -0.0%
drop-8388608-shared-half wall (ms) 220 / 224 / 231 194 / 200 / 211 -11.9%
drop-8388608-shared-half inner (ms) 77.0 / 79.2 / 81.0 51.0 / 52.6 / 56.1 -33.8%
drop-8388608-shared-half RSS (MiB) 330 / 331 / 331 330 / 331 / 331 0.0%
drop-1048576-unique-zero wall (ms) 17.8 / 18.1 / 18.5 17.8 / 17.9 / 18.3 -0.3%
drop-1048576-unique-zero inner (ms) 7.00 / 8.00 / 8.00 7.00 / 8.00 / 8.00 0.0%
drop-1048576-unique-zero RSS (MiB) 50.4 / 50.9 / 51.3 50.4 / 51.0 / 51.3 0.0%
drop-1048576-unique-over wall (ms) 15.9 / 16.3 / 17.2 16.1 / 16.4 / 16.9 1.6%
drop-1048576-unique-over inner (ms) 6.00 / 6.00 / 6.05 6.00 / 6.00 / 6.00 0.0%
drop-1048576-unique-over RSS (MiB) 50.5 / 51.3 / 51.5 50.9 / 51.2 / 51.3 0.8%
drop-1048576-shared-zero wall (ms) 27.6 / 28.0 / 28.5 27.8 / 28.0 / 28.3 0.4%
drop-1048576-shared-zero inner (ms) 10.0 / 10.0 / 10.0 10.0 / 10.0 / 10.0 0.0%
drop-1048576-shared-zero RSS (MiB) 50.1 / 50.8 / 51.4 50.3 / 50.6 / 51.1 0.4%
drop-1048576-shared-over wall (ms) 27.2 / 27.5 / 27.7 20.4 / 20.7 / 20.9 -25.0%
drop-1048576-shared-over inner (ms) 10.0 / 10.0 / 10.0 3.00 / 3.00 / 3.00 -70.0%
drop-1048576-shared-over RSS (MiB) 50.5 / 50.8 / 51.1 50.1 / 51.0 / 51.2 -0.8%
drop-1048576-prefix-before wall (ms) 30.9 / 31.8 / 32.6 31.0 / 31.8 / 32.7 0.2%
drop-1048576-prefix-before inner (ms) 10.0 / 11.0 / 11.0 11.0 / 11.0 / 11.0 10.0%
drop-1048576-prefix-before RSS (MiB) 50.5 / 51.1 / 51.4 50.0 / 51.0 / 51.4 -0.9%
drop-1048576-prefix-after wall (ms) 29.7 / 30.0 / 30.5 29.4 / 29.7 / 30.6 -1.0%
drop-1048576-prefix-after inner (ms) 10.0 / 11.0 / 11.0 10.0 / 10.0 / 10.1 0.0%
drop-1048576-prefix-after RSS (MiB) 50.3 / 51.1 / 51.3 50.5 / 51.3 / 51.4 0.5%

Reproduction

The following files are self-contained. Save each under .scratch/perf/string-drop-20261112/ in a checkout of this PR, then run:

export BEND_NO_TELEMETRY=1
d=.scratch/perf/string-drop-20261112
printf '.scratch/\n' >> "$(git rev-parse --git-path info/exclude)"
git fetch origin f311527776559ce40095108ad6a7514a6c34aaa1
git worktree add --detach "$d/base" f311527776559ce40095108ad6a7514a6c34aaa1
node "$d/generate-final.mjs"
node "$d/build-final.mjs"
uv run python "$d/measure.py" mac 20 final all

The summarizer expects both OSes, so run its last command after the Linux batch. It writes final/results.json. Keep pilot and interrupted files outside final/. The sampler records wall seconds and RSS MiB; tables above convert wall and inner time to milliseconds.

For Linux, build the Dockerfile below and capture its immutable ID. Its pinned Python base and tool versions recreate the setup; package mirrors can change, so check clang --version before comparing numbers. The measured image ID is recorded above, rather than claiming a rebuilt image has the same ID.

docker build --platform linux/arm64 -f "$d/Dockerfile" -t bend-drop-repro "$d"
image=$(docker inspect bend-drop-repro --format '{{.Id}}')
docker run --rm --platform linux/arm64 --cpus=4 --memory=8g --memory-swap=8g \
  -v "$PWD:/work" -w /work "$image" sh -c \
  'set -eu; d=.scratch/perf/string-drop-20261112; sh "$d/build-linux.sh"; uv run python "$d/measure.py" linux 20 final all'
uv run python "$d/summarize-final.py"
get-template.bend
import Base

# keys: P copies of 'a', then 4 letters from the low 16 bits of i
def pre(n: Nat, t: String) -> String:
  match n:
    case 0n:
      t
    case 1n+p:
      SCon{Chr{97}, pre(p, t)}

def hex(+i: U32, +s: Nat) -> Char:
  Chr{(97 + U32.and(U32.shrn(i, s), 15) : U32)}

def key(+p: Nat, +i: U32) -> String:
  pre(p, SCon{hex(i, 12n), SCon{hex(i, 8n), SCon{hex(i, 4n), SCon{hex(i, 0n), SNil{}}}}})

def build(n: Nat, +i: U32, +p: Nat, m: Map<&2, U32>) -> Map<&2, U32>:
  match n:
    case 0n:
      m
    case 1n+k:
      build(k, (i + 1 : U32), p, Map.set(&2, U32, m, key(p, i), i))

def look(n: Nat, +i: U32, +p: Nat, +acc: U32, r: Map<&2, U32> & U32) -> U32:
  match n:
    case 0n:
      (m, v) = r
      (acc + v : U32)
    case 1n+k:
      (m, v) = r
      look(k, (i + 1 : U32), p, (acc + v : U32), Map.get(U32, 0, m, key(p, U32.and((i * 7 : U32), 4095))))

def run(+p: Nat) -> IO(Unit):
  do IO<Unit>:
    m : Map<&2, U32> <- IO.pure(Map<&2, U32>, build(4096n, 0, p, Map.new(&2, U32)))
    start : Nat <- IO.now()
    sum : U32 <- IO.pure(U32, look(50000n, 0, p, 0, (m, 0)))
    end : Nat <- IO.now()
    IO.print(U32.show(sum))
    IO.print(Nat.show(Nat.sub(end, start)))

def main() -> IO(Unit):
  run(0n)
generate-final.mjs
import fs from 'node:fs';const d='.scratch/perf/string-drop-20261112';const manifest=[];
for(const p of[0,16,64,256])for(const miss of[false,true]){
 if(miss&&p!==64)continue;const id=`get-${p}${miss?'-miss':''}`;let source=fs.readFileSync(`${d}/get-template.bend`,'utf8').replace('run(0n)',`run(${p}n)`);
 if(miss)source=source.replace('key(p, U32.and((i * 7 : U32), 4095))','key(p, U32.add(4096, U32.and((i * 7 : U32), 4095)))');
 fs.writeFileSync(`${d}/${id}.bend`,source);
 manifest.push({id,expected:miss?0:Array.from({length:50000},(_,i)=>(i*7)&4095).reduce((a,b)=>(a+b)>>>0,0)});
}
const controls=[];
for(const n of[16,1024,65536,1048576,8388608])for(const mode of['unique','shared'])controls.push({n,mode,k:n/2,suffix:'half'});
for(const mode of['unique','shared'])for(const k of[0,1048577])controls.push({n:1048576,mode,k,suffix:k?'over':'zero'});
controls.push({n:1048576,mode:'prefix',k:32768,suffix:'before'});
controls.push({n:1048576,mode:'prefix',k:65538,suffix:'after'});
for(const{n,mode,k,suffix}of controls){
 const id=`drop-${n}-${mode}-${suffix}`;const shared=mode!=='unique',total=n+(mode==='prefix'?65536:0),expected=Math.max(0,total-k);
 const s=`import Base

def check(ok: Bool) -> IO(Unit):
  match ok:
    case True{}: IO.pure(Unit, Unit{})
    case False{}: IO.die(Unit, 1, "original changed")

def work(s: String) -> IO(Unit):
  do IO<Unit>:
    start : Nat <- IO.now()
    len : Nat <- IO.pure(Nat, String.length(String.drop(s, ${k}n)))
    end : Nat <- IO.now()
    IO.print(Nat.show(len))
    IO.print(Nat.show(Nat.sub(end, start)))

def main() -> IO(Unit):
  do IO<Unit>:
    ${shared?'+':''}s : String <- IO.pure(String, String.repeat("x", ${n}n))
    work(${mode==='prefix'?'String.repeat("p", 65536n) ++ s':'s'})
${shared?`    check(Nat.is_eq(String.length(s), ${n}n))\n`:''}`;
 fs.writeFileSync(`${d}/${id}.bend`,s);manifest.push({id,expected,n,k,mode});
}
fs.writeFileSync(`${d}/manifest.json`,JSON.stringify(manifest,null,2)+'\n');
measure.py
import csv,json,pathlib,subprocess,sys,time
p=pathlib.Path('.scratch/perf/string-drop-20261112');env=sys.argv[1];pairs=int(sys.argv[2]);folder=sys.argv[3];group=sys.argv[4] if len(sys.argv)>4 else 'all'
cases=json.loads((p/'manifest.json').read_text());cases.sort(key=lambda c:(0 if c['id']=='get-64' else 1 if c['id']=='get-256' else 2,c['id']))
for c in cases:
 if group!='all' and (c['id'].startswith('get'))!=(group=='get'):continue
 out=p/folder;out.mkdir(exist_ok=True);prefix='linux-' if env=='linux' else '';path=out/f'{env}-C-{c["id"]}.csv'
 if path.exists():
  rows=list(csv.DictReader(l for l in path.read_text().splitlines() if not l.startswith('#')))
  if len(rows)==2*pairs and all(r['exit']=='0' for r in rows) and len({(r['pair'],r['side']) for r in rows})==2*pairs:continue
  archive=p/'partial';archive.mkdir(exist_ok=True);path.rename(archive/f'{path.stem}-{time.time_ns()}.csv')
 subprocess.run([sys.executable,'.scratch/perf/string-drop-20261112/bench_pairs.py','--pairs',str(pairs),'--warmup','2','--base',str(p/f'{prefix}base-{c["id"]}'),'--branch',str(p/f'{prefix}branch-{c["id"]}'),'--expected',str(c['expected']),'--metrics','inner_s','--digest','--out',str(path)],check=True)
 print(env,c['id'],'PASS',flush=True)
summarize-final.py
import csv,json,pathlib,statistics
p=pathlib.Path('.scratch/perf/string-drop-20261112');cases=json.loads((p/'manifest.json').read_text());result=[]
for env in ['mac','linux']:
 for case in cases:
  file=p/'final'/f'{env}-C-{case["id"]}.csv';rows=list(csv.DictReader(l for l in file.read_text().splitlines() if not l.startswith('#')))
  assert len(rows)==40 and all(r['exit']=='0' for r in rows) and {(int(r['pair']),r['side']) for r in rows}=={(i,s) for i in range(1,21) for s in ['base','branch']}
  metrics={}
  for m in ['wall_s','inner_s','peak_rss_mib']:
   q={}
   for side in ['base','branch']:
    values=[float(r[m]) for r in rows if r['side']==side];cuts=statistics.quantiles(values,n=100,method='inclusive');q[side]=[cuts[49],cuts[79],cuts[94]]
   pairs={i:{r['side']:float(r[m]) for r in rows if int(r['pair'])==i} for i in range(1,21)}
   deltas=[v['branch']-v['base'] for v in pairs.values()]
   q.update(change_pct=(q['branch'][0]/q['base'][0]-1)*100 if q['base'][0] else None,paired_median=statistics.median(deltas),slower_pairs=sum(d>0 for d in deltas));metrics[m]=q
  result.append(dict(env=env,case=case['id'],metrics=metrics))
(p/'final'/'results.json').write_text(json.dumps(result,indent=2)+'\n')
print('AUDIT',len(result),'cases,',len(result)*40,'timedchildren, all20completepairs +exit0')
for x in result:
 if x['case'] in ['get-0','get-16','get-64','get-256','drop-8388608-unique-half','drop-8388608-shared-half']:
  print(x['env'],x['case'],{m:x['metrics'][m] for m in ['wall_s','peak_rss_mib']})
print('COSTS >5%+1ms wall or >5%+1MiB RSS')
for x in result:
 for m,absolute in [('wall_s',.001),('peak_rss_mib',1)]:
  v=x['metrics'][m]
  if v['change_pct'] is not None and v['change_pct']>5 and v['branch'][0]-v['base'][0]>absolute:print(x['env'],x['case'],m,v)
bench_pairs.py
"""Interleaved base/branch benchmark, the same on macOS and inside Linux containers.

usage: bench_pairs.py --pairs N --base "CMD" --branch "CMD" [--base-cwd D] [--branch-cwd D]
                      [--warmup K] [--metrics a,b] [--digest] --out FILE.csv

Each side has its own full command, so each side picks its own interpreter or build
(e.g. /base/.venv-linux/bin/python bench.py). Wall time is measured around the child
process only. peak_rss_mib is the largest resident set of one process: the child, or
the largest descendant it waited for (getrusage semantics). It is NOT the summed
memory of parallel workers, and it excludes GPU memory.

--metrics names values the child measures itself, printed on stdout as one line
`BENCH name=value name=value`. Use it when startup or data loading dominates the
process: e.g. `inner_s` (the timed call alone) and `rss_delta_mib` (how much the call
raised the peak RSS). Every listed metric must appear in every run.
--digest: the child also prints one line `DIGEST <hash>` of its output (e.g. md5 of the
results the user reads). Every measured run of both sides must print the same hash, or
the script reports "outputs differ" and exits 1: a speedup that changes output is a bug.
Exit 1 if any warm-up or measured run fails or a sample is invalid.
"""
import argparse, csv, hashlib, math, os, platform, shlex, subprocess, sys, tempfile, time

RSS_UNIT_BYTES = 1 if sys.platform == "darwin" else 1024  # ru_maxrss: bytes on macOS, KiB on Linux


def run_once(cmd, cwd):
    with tempfile.TemporaryFile() as err_file:  # a file, not a pipe: a chatty stderr cannot block the child
        start = time.perf_counter()
        proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=err_file)
        out = proc.stdout.read().decode(errors="replace")  # drain before wait so the pipe never blocks the child
        _, status, usage = os.wait4(proc.pid, 0)
        wall = time.perf_counter() - start
        err_file.seek(0)
        err = err_file.read().decode(errors="replace")[-400:]
    code = os.waitstatus_to_exitcode(status)
    return wall, usage.ru_maxrss * RSS_UNIT_BYTES / 2**20, code, err, out


def child_metrics(stdout, names):
    if names == ["inner_s"]:
        lines = stdout.splitlines()
        if len(lines) != 2:
            raise ValueError("expected checksum and elapsed milliseconds")
        return [int(lines[1]) / 1000]
    found = {}
    for line in stdout.splitlines():
        if line.startswith("BENCH "):
            found.update(kv.split("=", 1) for kv in line.split()[1:])
    missing = [n for n in names if n not in found]
    if missing:
        raise ValueError(f"child did not print BENCH {', '.join(missing)}")
    values = [float(found[n]) for n in names]
    if not all(math.isfinite(v) for v in values):
        raise ValueError("child printed a non-finite metric")
    return values


def child_digest(stdout):
    lines = stdout.splitlines()
    if len(lines) == 2 and lines[0].isdigit():
        return hashlib.sha256(lines[0].encode()).hexdigest()
    digests = [line.split(maxsplit=1)[1].strip() for line in stdout.splitlines() if line.startswith("DIGEST ")]
    if len(digests) != 1:
        raise ValueError(f"child printed {len(digests)} DIGEST lines, expected 1")
    return digests[0]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--pairs", type=int, required=True)
    ap.add_argument("--expected", type=int, required=True)
    ap.add_argument("--warmup", type=int, default=1, help="unreported runs per side; 0 for cold-start cases")
    ap.add_argument("--base", required=True); ap.add_argument("--branch", required=True)
    ap.add_argument("--base-cwd", default="."); ap.add_argument("--branch-cwd", default=".")
    ap.add_argument("--metrics", default="", help="comma-separated names the child prints as BENCH name=value")
    ap.add_argument("--digest", action="store_true", help="child prints DIGEST <hash>; all runs must match")
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    if a.pairs < 1 or a.warmup < 0:
        ap.error("--pairs must be >= 1 and --warmup >= 0")
    metric_names = [m for m in a.metrics.split(",") if m]
    sides = {"base": (shlex.split(a.base), a.base_cwd), "branch": (shlex.split(a.branch), a.branch_cwd)}

    for name, (cmd, cwd) in sides.items():
        for _ in range(a.warmup):
            *_, code, err, _ = run_once(cmd, cwd)
            if code != 0:
                sys.exit(f"warm-up failed on {name} (exit {code}): {err}")

    failed = False
    digests = {"base": set(), "branch": set()}
    with open(a.out, "w", newline="") as f:
        f.write(f"# {platform.system()} {platform.machine()} python {platform.python_version()} warmup={a.warmup}\n")
        w = csv.writer(f); w.writerow(["pair", "side", "wall_s", "peak_rss_mib", *metric_names, "exit"])
        for i in range(1, a.pairs + 1):
            order = ("base", "branch") if i % 2 else ("branch", "base")  # alternate who goes first
            for name in order:
                wall, rss, code, err, out = run_once(*sides[name])
                extra = [""] * len(metric_names)
                if code == 0:
                    try:
                        if int(out.splitlines()[0]) != a.expected:
                            raise ValueError("checksum differs from independent expected sum")
                        extra = [f"{v:.6g}" for v in child_metrics(out, metric_names)]
                        if a.digest:
                            digests[name].add(child_digest(out))
                    except ValueError as e:
                        code, err = 99, str(e)
                w.writerow([i, name, f"{wall:.4f}", f"{rss:.1f}", *extra, code])
                f.flush()
                if code != 0:
                    failed = True; print(f"pair {i} {name} exit {code}: {err}", file=sys.stderr)
    if a.digest and len(digests["base"] | digests["branch"]) > 1:
        failed = True
        print(f"outputs differ: base {sorted(digests['base'])} branch {sorted(digests['branch'])}", file=sys.stderr)
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()
build-final.mjs
import fs from 'node:fs';import{spawnSync}from'node:child_process';const d='.scratch/perf/string-drop-20261112';
for(const{id}of JSON.parse(fs.readFileSync(`${d}/manifest.json`)))for(const side of['base','branch']){
 const main=side==='base'?`${d}/base/bend2/main.ts`:'bend2/main.ts';const out=`${d}/${side}-${id}`;
 for(const[cmd,args]of[['bun',[main,`${d}/${id}.bend`,'-o',out+'.c','-o',out+'.js']],['clang',['-O3','-g','-std=c11',out+'.c','-lpthread','-lm','-o',out]]]){const r=spawnSync(cmd,args,{encoding:'utf8',env:{...process.env,BEND_NO_TELEMETRY:'1'}});if(r.status)throw Error(r.stdout+r.stderr);}
 if(side==='branch'&&fs.readFileSync(`${d}/base-${id}.js`,'utf8')!==fs.readFileSync(`${d}/branch-${id}.js`,'utf8'))throw Error('JS differs '+id);console.log(out);
}
build-linux.sh
#!/bin/sh
set -eu
d=.scratch/perf/string-drop-20261112
for id in $(node -p "require('./$d/manifest.json').map(x=>x.id).join(' ')"); do
  for side in base branch; do
    clang -O3 -g -std=c11 "$d/$side-$id.c" -lpthread -lm -o "$d/linux-$side-$id"
  done
done
Dockerfile
FROM python@sha256:4840d514c583a4d3d8cad3940e68dee6f0f6f3635c12fcd0a3d74c21a5b93a54
RUN apt-get update && apt-get install -y --no-install-recommends clang curl unzip xz-utils \
 && rm -rf /var/lib/apt/lists/*
RUN curl -fsSL https://bun.sh/install | bash -s "bun-v1.4.2"
COPY --from=ghcr.io/astral-sh/uv:0.13.7 /uv /uvx /usr/local/bin/
RUN curl -fsSL https://nodejs.org/dist/v25.9.0/node-v25.9.0-linux-arm64.tar.xz -o /tmp/node.tar.xz \
 && curl -fsSL https://nodejs.org/dist/v25.9.0/SHASUMS256.txt -o /tmp/node.sha \
 && grep ' node-v25.9.0-linux-arm64.tar.xz$' /tmp/node.sha | sed 's|node-v25.9.0-linux-arm64.tar.xz|/tmp/node.tar.xz|' | sha256sum -c - \
 && tar -xJf /tmp/node.tar.xz --strip-components=1 -C /usr/local \
 && rm /tmp/node.tar.xz /tmp/node.sha
ENV PATH="/root/.bun/bin:$PATH"

@sebastianbreguel

Copy link
Copy Markdown
Contributor Author

@nicolas-abril could you review this PR?

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Thanks for this, and for the careful measurements. The diagnosis is right: String.drop on a shared string pays per cell where it should pay once, and your str_drop shows what the fast path looks like. We're closing it because String.drop written in Bend can and should be as fast as the C function, so we'd rather improve the compiler than add another intrinsic. #2134 does that: the emitted loop borrows from the first shared cell on, and it matches this PR on the Map.get and half-drop workloads (138.3 ms and 376.3 ms against 138.0 ms and 377.7 ms here). The work itself was good, and your fixture is the basis of the test there.

Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants