You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(c): borrow shared tails in String.drop - #2131
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)
"""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.csvEach 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 childprocess only. peak_rss_mib is the largest resident set of one process: the child, orthe largest descendant it waited for (getrusage semantics). It is NOT the summedmemory 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 theprocess: e.g. `inner_s` (the timed call alone) and `rss_delta_mib` (how much the callraised 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 theresults the user reads). Every measured run of both sides must print the same hash, orthe 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."""importargparse, csv, hashlib, math, os, platform, shlex, subprocess, sys, tempfile, timeRSS_UNIT_BYTES=1ifsys.platform=="darwin"else1024# ru_maxrss: bytes on macOS, KiB on Linuxdefrun_once(cmd, cwd):
withtempfile.TemporaryFile() aserr_file: # a file, not a pipe: a chatty stderr cannot block the childstart=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() -starterr_file.seek(0)
err=err_file.read().decode(errors="replace")[-400:]
code=os.waitstatus_to_exitcode(status)
returnwall, usage.ru_maxrss*RSS_UNIT_BYTES/2**20, code, err, outdefchild_metrics(stdout, names):
ifnames== ["inner_s"]:
lines=stdout.splitlines()
iflen(lines) !=2:
raiseValueError("expected checksum and elapsed milliseconds")
return [int(lines[1]) /1000]
found= {}
forlineinstdout.splitlines():
ifline.startswith("BENCH "):
found.update(kv.split("=", 1) forkvinline.split()[1:])
missing= [nforninnamesifnnotinfound]
ifmissing:
raiseValueError(f"child did not print BENCH {', '.join(missing)}")
values= [float(found[n]) forninnames]
ifnotall(math.isfinite(v) forvinvalues):
raiseValueError("child printed a non-finite metric")
returnvaluesdefchild_digest(stdout):
lines=stdout.splitlines()
iflen(lines) ==2andlines[0].isdigit():
returnhashlib.sha256(lines[0].encode()).hexdigest()
digests= [line.split(maxsplit=1)[1].strip() forlineinstdout.splitlines() ifline.startswith("DIGEST ")]
iflen(digests) !=1:
raiseValueError(f"child printed {len(digests)} DIGEST lines, expected 1")
returndigests[0]
defmain():
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()
ifa.pairs<1ora.warmup<0:
ap.error("--pairs must be >= 1 and --warmup >= 0")
metric_names= [mformina.metrics.split(",") ifm]
sides= {"base": (shlex.split(a.base), a.base_cwd), "branch": (shlex.split(a.branch), a.branch_cwd)}
forname, (cmd, cwd) insides.items():
for_inrange(a.warmup):
*_, code, err, _=run_once(cmd, cwd)
ifcode!=0:
sys.exit(f"warm-up failed on {name} (exit {code}): {err}")
failed=Falsedigests= {"base": set(), "branch": set()}
withopen(a.out, "w", newline="") asf:
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"])
foriinrange(1, a.pairs+1):
order= ("base", "branch") ifi%2else ("branch", "base") # alternate who goes firstfornameinorder:
wall, rss, code, err, out=run_once(*sides[name])
extra= [""] *len(metric_names)
ifcode==0:
try:
ifint(out.splitlines()[0]) !=a.expected:
raiseValueError("checksum differs from independent expected sum")
extra= [f"{v:.6g}"forvinchild_metrics(out, metric_names)]
ifa.digest:
digests[name].add(child_digest(out))
exceptValueErrorase:
code, err=99, str(e)
w.writerow([i, name, f"{wall:.4f}", f"{rss:.1f}", *extra, code])
f.flush()
ifcode!=0:
failed=True; print(f"pair {i}{name} exit {code}: {err}", file=sys.stderr)
ifa.digestandlen(digests["base"] |digests["branch"]) >1:
failed=Trueprint(f"outputs differ: base {sorted(digests['base'])} branch {sorted(digests['branch'])}", file=sys.stderr)
sys.exit(1iffailedelse0)
if__name__=="__main__":
main()
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
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:
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.
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
Docker Linux arm64
Reproduction
The following files are self-contained. Save each under .scratch/perf/string-drop-20261112/ in a checkout of this PR, then run:
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.
get-template.bend
generate-final.mjs
measure.py
summarize-final.py
bench_pairs.py
build-final.mjs
build-linux.sh
Dockerfile