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][P1] Array mutation is O(n²) and ${#arr[@]} is O(n): a[i]= / a+=() 39-666× slower, length query ~230× — dual-store capture-replay replays per element write #616
Two independent deformities in the array path, measured on-device (Android/Termux, rubash from master 334afab, GNU bash 5.3.20 reference, idle best-of-3):
1. Array element build/append is O(n²) — a[i]=$i and a+=("$i") both:
n (elements)
rubash a[i]=
rubash a+=()
GNU bash
× slower
250
61 ms
—
25 ms
2.4×
500
144 ms
—
34 ms
4.2×
1 000
444 ms
—
37 ms
12×
2 000
1 723 ms
1 710 ms
44 ms
39×
10 000
~44 s
—
66 ms
~666×
Doubling n grows time ~2.4× → ~3.9× (super-linear, approaching 4× = O(n²)). GNU bash is flat at ~6.6 µs/element.
2. ${#arr[@]} length query is O(n), not O(1) — 20 000 queries:
array size n
rubash
GNU bash
100
2 455 ms
—
1 000
22 579 ms
—
5 000
>30 s (timeout)
97 ms (n=5 000)
Scales ~10× per 10× array size → O(n) per query (~1.2 µs per element per query), vs bash's O(1). Combined with (1) any array-processing loop is effectively O(n²)-to-O(n³). Array iteration itself (for v in "${a[@]}", isolated via brace-built array) is fine (1.5×) — the pathology is purely mutation and length.
Root-cause pointer: the array/assoc element set goes through the engine's dual-store + capture-replay diff-sync (src/executor/array_assignment_exec.rs → shell_state.env_vars, mirrors temporary_assignments.rs / variable_state.rs dual BTreeMap+HashMap with replay). If every element write re-derives/diffs the whole variable (same machinery #609/#607 flag for scalars), that's the O(n) per-op → O(n²) build. The length query likely materializes/re-scan the array each call.
Suggested fix direction: (a) amortized growth / capacity-doubling for index-append, and a mutation fence around the capture-replay path for a sequence of loop-local element writes (batch the diff once per loop-level command); (b) maintain an O(1) element-count counter for ${#arr[@]} (insertion/removal bookkeeping) instead of recomputing.
Repro
rubash -c 'a=(); for((i=0;i<2000;i++)); do a[i]=$i; done' # ~1.7 s vs bash 44 ms
rubash -c 'a=({1..1000}); for((i=0;i<20000;i++)); do n=${#a[@]}; done' # 22.6 s vs bash ~100 ms
Line-level attribution (the root is the storage model, not a per-op bug)
Arrays and assoc arrays are stored as a single rendered string in the scalar env_vars table, so every element operation re-parses or re-renders the whole thing — O(n) per op.
${#arr[@]} length (expand_braced_indices.rs:439 → arrays/executor.rs:362 array_length) calls array_values(&value).len(). arrays/storage.rs:16 array_values does split_storage_words(inner) → full O(n) parse into Vec<String> on every length query. Confirmed scaling over 20 000 queries: n=100 → 2 455 ms, n=1000 → 22 579 ms (~10x per 10x elements = O(n)); GNU is O(1).
a[i]=$i / a+=() build (array_assignment_exec.rs:65 execute_array_element_assignment) re-derives the array's rendered string and re-parses it on every write — O(n) per write → O(n^2) build. Confirmed: n doubling 250/500/1000/2000 → 61/144/444/1 723 ms (≈2.4x→3.9x, heading to 4x = O(n^2)); n=10 000 ≈44 s vs bash 66 ms. GNU bash appends in O(1) amortized ≈6.6 µs/element.
The codebase already knows this is a stopgap: arrays/storage.rs comment "lossy representation used while arrays are still stored in the scalar variable table".
Fix is design-level (not a localized patch): migrate indexed arrays to structured storage (Vec<String> + O(1)-amortized append + maintained length / -1-sentinel indexed) and assoc to a HashMap/BTreeMap with an O(1) count, so array_length is O(1) and element writes are O(1)-amortized. Until then, any per-op count/append remains O(n). An incremental mitigation on the current string model (append-aware fast path + cached length side-table) is possible but limited and needs care with the dual-store replay that #609 flags. Recommend the storage migration as the real fix; happy to draft the design + test plan.
Appendix: full array/assoc storage migration surface
Line-level map of every reader/writer of the rendered-string storage — the input for the structured-storage migration (plan Phase 1).
Storage type (where the typed variant must go)
ShellState.env_vars: VarTable — src/shell/state.rs:40; VarTable { values: HashMap<String, String>, attrs } (src/shell/var_table.rs:136). A value can only be a string — this is the constraint that forces every op through render/parse.
Array storage producers: store_indexed_array (arrays/storage.rs:274, via format_indexed_array_values at :249) and assoc: format_assoc_storage (assignment_helpers.rs:345).
already bypasses storage (array_length:369 fast path)
Note: the content-addressed caches miss on every write (each write produces a new string), so they only help read-heavy hot loops over unchanged arrays — they cannot fix the O(n) build.
Writers (re-render the whole array per write → O(n²) builds)
writer
location
operation
store_indexed_array
storage.rs:274
init (init.rs:641-655), mapfile/completion (job_builtins.rs:2347/2490), public accessors (public_accessors.rs:568-721)
element assign
array_assignment_exec.rs:504 (+arrays.rs:781)
a[i]=v: parse old (cache) → mutate → format_indexed_array_values → env_vars.insert — full re-render per element
Indexed: ARRAY sparse doubly-linked list with maintained num_elements field — length is a macro, O(1) (array.h:30-41, array.h:121; insert/del maintain it array.c:533-629); lastref roving pointer makes repeated access amortized O(1); negative subscripts resolved as max_index+1+ind.
Assoc: HASH_TABLE with maintained nentries (assoc.c) — insert/lookup O(1) by hash bucket; ${a[*]} iteration order = bucket order.
Rust migration target: VarTable.values → enum ShellValue = Scalar(String) | Indexed{elems, max_index, count} | Assoc{map, count} (or a side-table to avoid touching every HashMap<String,String> call site at once), with render-on-demand fallback for the builtin printers (declare -p, @A) so the 20+ reader call sites migrate incrementally: length O(1) first, element assign in-place second, assoc map third.
Suggested incremental PR slicing (updates plan Phase 1)
1a typed storage behind parameter_array_storage accessor + render fallback (no behavior change, gates must stay identical);
1b${#a[@]} O(1) via maintained count (kills the per-call array_values().len());
perf(array): the indexed array gains a structured cell in the existing typed
store (ShellState.variables / ShellValue::IndexedArray), so ${#a[@]} reads
a maintained count (GNU array.h:121array_num_elements) instead of splitting
the render.
Invariant: the cell is either a complete mirror of the same indexed_array_entries parse the render uses, or absent. Writes always
sync or drop; a refused (readonly) write drops the cell rather than shadowing
the mirror. RUBASH_ARRAY_STORE=0 disables the structured reads.
All CI checks pass; lib 581/581; cli_tests red set name-identical to master; executor_tests failure set identical (set-compared); 2500-script
differential fuzz branch == master.
Phase 1b — element write is now O(log n) (not in #627 yet)
Attribution first: the element path (array_assignment_exec.rs) did four
O(n) operations per write — a mirror String clone, an indexed_array_entries
deep copy, a full format_indexed_array_storage render, and the env_vars
insert — so building an n-element array was O(n²). GNU touches one node
(array.c:516 array_insert) and maintains num_elements
(array.h:121); nothing is re-serialised.
Fix: when the structured cell is a completeIndexedArray, the mirror is a canonicalSTORAGE_WORD_PREFIX render, and the write is an append
(index == max_index + 1), the cell is extended by one key and the mirror is
extended in place by exactly the segment the renderer would have appended.
Every other shape (overwrite, sparse insert, readonly, missing cell,
non-canonical mirror) falls through to the unchanged full path — a whitelist
whose fallback is the real path, not a symptom blacklist.
Measured on the 15_arrbuild construct (a[i]=$i, n=2000): master 2009 ms
→ branch 66 ms, i.e. 30x faster than master and now 1.65x GNU bash.
Full A/B table plus the byte-identity verification (the in-place segment is
proven identical to a full re-render via declare -p) will follow with the PR.
Unrelated pre-existing bug found while probing: #629
a=(); for v in 'he said "hi"'; do a+=("$v"); done stores byte 0x18
(DATA_DQUOTE carrier) where bash stores " — a silent value corruption. It
reproduces identically on 6daf8e1, so it is not from this work; reported with
a minimal repro rather than patched, because the carrier protocol is the #117-family high-risk area and needs a GNU-source attribution first.
Phase 1a — perf(array): O(1) ${#a[@]} via the typed indexed cell — merged as 14209b9 (#627). The array's structured cell now rides the existing typed store
(ShellState.variables, ShellValue::IndexedArray) instead of adding a third
truth; env_vars stays the projection every storage reader sees. Invariant: the
cell is either a complete mirror of the same parse the render uses, or absent — writes sync or drop, only reads consult the gate
(RUBASH_ARRAY_STORE=0 disables the reads).
Phase 1b — perf(1b): amortise the indexed element write — open as #630.
Element writes no longer re-parse and re-render the whole array: an append onto a
canonical mirror is now one structured insert plus the exact segment the renderer
would have appended (GNU arrayfunc.c:815 assign_array_element → array.c:516 array_insert; the ARRAY object is the array, nothing is re-serialised).
No row regresses, and the build path is no longer quadratic: master goes
1760 → 46071 ms for 5x the elements (26x), the branch 51 → 157 ms (3.1x).
The construct that motivated #616 — 10k array + 200k ${#a[@]} reads — is masterNA (>300 s) vs branch 2274 ms (3.86x GNU): the branch is the only
build that completes.
Measurement correction (worth recording in the issue)
The harness used to always run bash, master, branch. This host throttles: the same binary measures ~1.14x slower merely for being invoked later in a round,
which an always-last branch reports as a phantom ~15% regression. The harness now
rotates the shell order per round. Two "regressions" I nearly reported were this
artefact, and rotation then exposed a real self-inflicted cost that I removed:
the sync rebuilt the whole structured cell per write, so the compound append a+=(...) copied the whole array per iteration — fixed with a verified-tailed
refresh (extend_indexed_array_from_parsed, prefix checked key-by-key);
the element write rebuilt the BTreeMap per write — fixed with an in-place
single-key extension.
Gates
rubash: lib 581/581; tests/array_store_parity.rs (42 GNU-verified cases) green
with the store on and off; cli_tests red-set and executor_tests failure-set
identical to master 14209b9; 2500-seed differential fuzz branch==master
0/2500 (bash-diff 677==677).
niubash (product; niu rebuilt against this branch vs master, same niubash): probes.shPASS=97 with an identical structural-diff set (4 pre-existing: mx-printf-fmt-var, mx-enable-f, mx-pushd, mx-set-c); interactive2.sh
converges to the identical stable failure set (hist-persist, repl-handoff, tab-file) with ctrl-c-ok flaky on both sides across runs. Element build
through the product shell: 10135 ms (master) → 124 ms (branch) for n=4000.
Oracle caveat: the reference here is GNU Bash 5.3.20 (this host), not the
repo's designated WSL 5.3.0; these Termux/Android figures are not Windows/Linux
x86_64 validation.
Still open
The compound append (a+=(...)) and a mid-array overwrite (a[3]=x) still
re-render the whole mirror, so both remain O(n) per write; the structured cell
itself is now incremental. Phase 1c.
The root fix for both is a lazily materialised mirror, which needs a
materialisation point at every whole-table consumer — a design of its own.
Phase 1c is up: #632 (perf/compound-append-in-place, 557374d, on top of 1b 37d6caf).
The remaining quadratic write. 1b's "not addressed here" named it: a+=(...) still re-parsed and re-rendered the whole mirror, so the loop idiom a+=($i) was O(n²). Measured on untouched master: cmp2000 1985 ms, cmp4000 8175 ms — 4.12x for 2x the elements (quadratic), 50.9x / 190.1x GNU (39 / 43 ms).
Cause.append_array_value opened with indexed_array_entries(current) (whole-mirror parse into a BTreeMap) and the caller then re-rendered and re-synced the cell — three O(n) passes per element appended. The parse is memoised and each render feeds it back, so master's is a hit; it is still as_ref().clone() of the whole map. GNU edits the ARRAY object in place (assign_compound_array_list, arrayfunc.c:700; last_ind = array_max_index(a) + 1, arrayfunc.c:743; array_insert, array.c:516) and never re-serialises — and that ARRAY object is rubash's structured cell.
Fix. Seed the decode from the structured cell (the 1a "complete or absent" invariant that 1b already relies on) and hold this call's writes in a small mutations map, so no element map is built; then grow the canonical mirror by exactly the renderer's segments (append_indexed_mirror_segments, 1b's helper generalised to a segment list) and extend the cell. Every other shape — an overwrite at or below the old max, an integer array, no cell, a non-canonical mirror, readonly — falls back to the unchanged render path.
Measured (order-rotated best-of-9, release, same tree, bash 5.3.20):
case
bash
master
branch
master/branch
cmp2000
39
1985
68
29.2x
cmp4000
43
8175
95
86.1x
cmp_literal2000
34
1979
63
31.4x
elem2000_ctl (1b control)
33
61
55
1.11x
No row regresses and the 1b control is unchanged. The shape is the point: master 1985 → 8175 ms for 2x the elements (4.12x, quadratic), branch 68 → 95 ms (1.40x, ~linear). cmp2000 is now 1.7x GNU instead of 50.9x.
Gates. lib 584/584; array_store_parity (54 GNU-verified cases, +12 for 1c) green on and off; cli_tests 0 new failures and executor_tests 0 new failures vs master; 52-case whole-class differential matrix 0 branch != master; 2500-seed fuzz branch != master 0/2500 with bash != branch == bash != master.
Measurement note worth keeping: this suite must be compared serially. At --test-threads=4executor_tests races on shared paths under target/ (e.g. target/rubash-lineno-assignment-output.txt: No such file or directory) and reported 2 phantom cli_tests "regressions" plus 4 new / 6 disappeared executor_tests rows — every one passes in isolation and none is related to this change.
Filed separately while building the 1c matrix:#631 — a compound assignment with an out-of-range negative subscript (a=(); a+=([-1]=x)) is silently dropped where GNU reports bad array subscript (arrayfunc.c:801-809) and exits 1. Pre-existing on master, unrelated to the store; kept out of this perf PR so it stays one concern.
Follow-up after syncing current master 12da0b5 (Niubash6295367): the previously reported PR627 unset-all regression is STILL reproducible in the latest product build.
Using the original script file target/issue359/pr627-probe.sh: initialize three indexed elements; unset a[@]; print length; repeat with a[*].
RUBASH_ARRAY_STORE=1: stdout 3 then 3, rc0, empty stderr.
RUBASH_ARRAY_STORE=0: stdout 0 then 0, rc0, empty stderr.
Designated GNU5.3.0 had already returned 0 then 0 for this same script in the original review. Current unset_arrays.rs flush branch still updates env_vars and returns without synchronizing the typed cell.
The existing array_store_parity (2 harness tests) and issue631 regression (9 tests) both pass, so those suites do not cover this omission. This is an outstanding correctness blocker, not an integration/text conflict; please do not treat phase1a/1b/1c merges or their benchmarks as proving all write routes correct.
Two things the recon paid for: (1) the battery caught a live sparse-compound dense-cell bug on master (a=([5]=x [2]=y); a[2]=z duplicated) — fixed in-PR as the cell-trust precondition; the unset-flush sibling is #651, not bundled. (2) indexed readers fold by construction, so no parse/render changes — only the two verbatim printers needed a fold-before-print.
Landed as #652 (squash-merged bc258ad). Indexed overwrite curve is flat: K=5000 177x vs master, GNU gap 674x -> 3.8x. Precondition fix included (declare-seeded dense cells); unset-flush sibling tracked in #651.
Re-measured on niubash 1.4.4 / Termux aarch64: indexed writes 2k at 2.26x, ${#arr[@]} on 5k at 2.14x; scaling append 2500/5000/10000 gives ~1.6x per doubling in BOTH shells (= linear). Steady ~2.1-2.3x overhead remains but no n^2 signature at these sizes — may be fixed or size-dependent.
Activity
caomengxuan666 commentedon Oct 15, 2026
Line-level attribution (the root is the storage model, not a per-op bug)
Arrays and assoc arrays are stored as a single rendered string in the scalar
env_varstable, so every element operation re-parses or re-renders the whole thing — O(n) per op.${#arr[@]}length (expand_braced_indices.rs:439→arrays/executor.rs:362 array_length) callsarray_values(&value).len().arrays/storage.rs:16 array_valuesdoessplit_storage_words(inner)→ full O(n) parse intoVec<String>on every length query. Confirmed scaling over 20 000 queries: n=100 → 2 455 ms, n=1000 → 22 579 ms (~10x per 10x elements = O(n)); GNU is O(1).a[i]=$i/a+=()build (array_assignment_exec.rs:65 execute_array_element_assignment) re-derives the array's rendered string and re-parses it on every write — O(n) per write → O(n^2) build. Confirmed: n doubling 250/500/1000/2000 → 61/144/444/1 723 ms (≈2.4x→3.9x, heading to 4x = O(n^2)); n=10 000 ≈44 s vs bash 66 ms. GNU bash appends in O(1) amortized ≈6.6 µs/element.assoc_hash_ordered_valuesre-deriving the hash order (arrays/executor.rsassoc_subscript_range_values) per op.The codebase already knows this is a stopgap:
arrays/storage.rscomment "lossy representation used while arrays are still stored in the scalar variable table".Fix is design-level (not a localized patch): migrate indexed arrays to structured storage (
Vec<String>+ O(1)-amortized append + maintained length / -1-sentinel indexed) and assoc to aHashMap/BTreeMapwith an O(1) count, soarray_lengthis O(1) and element writes are O(1)-amortized. Until then, any per-op count/append remains O(n). An incremental mitigation on the current string model (append-aware fast path + cached length side-table) is possible but limited and needs care with the dual-store replay that #609 flags. Recommend the storage migration as the real fix; happy to draft the design + test plan.caomengxuan666 commentedon Oct 15, 2026
Appendix: full array/assoc storage migration surface
Line-level map of every reader/writer of the rendered-string storage — the input for the structured-storage migration (plan Phase 1).
Storage type (where the typed variant must go)
ShellState.env_vars: VarTable—src/shell/state.rs:40;VarTable { values: HashMap<String, String>, attrs }(src/shell/var_table.rs:136). A value can only be a string — this is the constraint that forces every op through render/parse.store_indexed_array(arrays/storage.rs:274, viaformat_indexed_array_valuesat :249) and assoc:format_assoc_storage(assignment_helpers.rs:345).Readers (parse the storage string per call)
array_values(&str) -> Vec<String>arrays/storage.rs:16array_length(arrays/executor.rs:373),"${a[@]}"expansion (executor.rs:54, 633, 644, 679, 798, 888),slice_array_values(arrays.rs:1292)indexed_array_entries(&str) -> BTreeMap<usize,String>arrays/storage.rs:50_cached:64, 128-entry content-addressed cache)declare.rs:101/161,declare/assign.rs:278/281/625/693/853,declare/storage/array.rs:39,setattr/value.rs:96,arithmetic/value.rs:671,array_assignment_exec.rs:504,arrays.rs:781/1270,executor.rs:110/914PIPESTATUS,BASH_LINENO, …)dynamic_arrays.rs:526-573array_length:369fast path)Note: the content-addressed caches miss on every write (each write produces a new string), so they only help read-heavy hot loops over unchanged arrays — they cannot fix the O(n) build.
Writers (re-render the whole array per write → O(n²) builds)
store_indexed_arraystorage.rs:274init.rs:641-655),mapfile/completion (job_builtins.rs:2347/2490), public accessors (public_accessors.rs:568-721)array_assignment_exec.rs:504(+arrays.rs:781)a[i]=v: parse old (cache) → mutate →format_indexed_array_values→env_vars.insert— full re-render per elementdeclare -a/compound assignbuiltins/declare/assign.rs:278-853,setattr/value.rs:96array_assignment_exec.rs:356-359(format_assoc_storage)A[k]=v: full hash re-render per write → #618's 17×Hot-path vs cosmetic
${#a[@]}(array_length→array_values().len()— uncached O(n) per call, unlikeindexed_array_entries),a[i]=build (O(n²)),"${a[@]}"iterate (O(n) inherent — fine),A[k]=vbuild.declare -p/@Arender (rare).Target model (GNU reference,
third_party/bash/)ARRAYsparse doubly-linked list with maintainednum_elementsfield — length is a macro, O(1) (array.h:30-41,array.h:121; insert/del maintain itarray.c:533-629);lastrefroving pointer makes repeated access amortized O(1); negative subscripts resolved asmax_index+1+ind.HASH_TABLEwith maintainednentries(assoc.c) — insert/lookup O(1) by hash bucket;${a[*]}iteration order = bucket order.VarTable.values→ enumShellValue = Scalar(String) | Indexed{elems, max_index, count} | Assoc{map, count}(or a side-table to avoid touching everyHashMap<String,String>call site at once), with render-on-demand fallback for the builtin printers (declare -p,@A) so the 20+ reader call sites migrate incrementally: length O(1) first, element assign in-place second, assoc map third.Suggested incremental PR slicing (updates plan Phase 1)
parameter_array_storageaccessor + render fallback (no behavior change, gates must stay identical);${#a[@]}O(1) via maintained count (kills the per-callarray_values().len());declare -p/@A.docs(perf): record the #616 Phase 1a measurement and invariant
caomengxuan666 commentedon Oct 15, 2026
Phase 1a — PR #627 (open, CI green)
perf(array): the indexed array gains a structured cell in the existing typedstore (
ShellState.variables/ShellValue::IndexedArray), so${#a[@]}readsa maintained count (GNU
array.h:121array_num_elements) instead of splittingthe render.
indexed_array_entriesparse the render uses, or absent. Writes alwayssync or drop; a refused (readonly) write drops the cell rather than shadowing
the mirror.
RUBASH_ARRAY_STORE=0disables the structured reads.cli_testsred set name-identical to master;executor_testsfailure set identical (set-compared); 2500-scriptdifferential fuzz branch == master.
docs/perf-issue-616-array-store.md(in perf(array): O(1) ${#a[@]} via the typed indexed cell, zero behaviour change (#616 Phase 1a) #627).Phase 1b — element write is now O(log n) (not in #627 yet)
Attribution first: the element path (
array_assignment_exec.rs) did fourO(n) operations per write — a mirror
Stringclone, anindexed_array_entriesdeep copy, a full
format_indexed_array_storagerender, and theenv_varsinsert — so building an n-element array was O(n²). GNU touches one node
(
array.c:516 array_insert) and maintainsnum_elements(
array.h:121); nothing is re-serialised.Fix: when the structured cell is a complete
IndexedArray, the mirror is acanonical
STORAGE_WORD_PREFIXrender, and the write is an append(
index == max_index + 1), the cell is extended by one key and the mirror isextended in place by exactly the segment the renderer would have appended.
Every other shape (overwrite, sparse insert, readonly, missing cell,
non-canonical mirror) falls through to the unchanged full path — a whitelist
whose fallback is the real path, not a symptom blacklist.
Measured on the
15_arrbuildconstruct (a[i]=$i, n=2000): master 2009 ms→ branch 66 ms, i.e. 30x faster than master and now 1.65x GNU bash.
Full A/B table plus the byte-identity verification (the in-place segment is
proven identical to a full re-render via
declare -p) will follow with the PR.Unrelated pre-existing bug found while probing: #629
a=(); for v in 'he said "hi"'; do a+=("$v"); donestores byte0x18(
DATA_DQUOTEcarrier) where bash stores"— a silent value corruption. Itreproduces identically on
6daf8e1, so it is not from this work; reported witha minimal repro rather than patched, because the carrier protocol is the
#117-family high-risk area and needs a GNU-source attribution first.
perf(1a): refresh the indexed cell incrementally on append-shaped wri…
docs(perf): correct the #616 A/B for measurement-order bias (#616)
perf(array): O(1) ${#a[@]} via the typed indexed cell (#616 Phase 1a)
perf(1b): amortise the indexed element write with the structured cell (…
caomengxuan666 commentedon Oct 15, 2026
#616 status: Phase 1a merged, Phase 1b in review
Phase 1a —
perf(array): O(1) ${#a[@]} via the typed indexed cell— merged as14209b9(#627). The array's structured cell now rides the existing typed store(
ShellState.variables,ShellValue::IndexedArray) instead of adding a thirdtruth;
env_varsstays the projection every storage reader sees. Invariant: thecell is either a complete mirror of the same parse the render uses, or
absent — writes sync or drop, only reads consult the gate
(
RUBASH_ARRAY_STORE=0disables the reads).Phase 1b —
perf(1b): amortise the indexed element write— open as #630.Element writes no longer re-parse and re-render the whole array: an append onto a
canonical mirror is now one structured insert plus the exact segment the renderer
would have appended (GNU
arrayfunc.c:815 assign_array_element→array.c:516 array_insert; theARRAYobject is the array, nothing is re-serialised).Measured (order-rotated best-of-5, Termux/Android aarch64, release)
${#s}scalar control (200k)build10kcompound +${#a[@]}${#a[@]}b=("${a[@]}")×2000, n=2000${#a[@]}, n=5000No row regresses, and the build path is no longer quadratic:
mastergoes1760 → 46071 ms for 5x the elements (26x), the branch 51 → 157 ms (3.1x).
The construct that motivated #616 — 10k array + 200k
${#a[@]}reads — ismasterNA (>300 s) vs branch 2274 ms (3.86x GNU): the branch is the onlybuild that completes.
Measurement correction (worth recording in the issue)
The harness used to always run
bash, master, branch. This host throttles: thesame binary measures ~1.14x slower merely for being invoked later in a round,
which an always-last branch reports as a phantom ~15% regression. The harness now
rotates the shell order per round. Two "regressions" I nearly reported were this
artefact, and rotation then exposed a real self-inflicted cost that I removed:
a+=(...)copied the whole array per iteration — fixed with a verified-tailedrefresh (
extend_indexed_array_from_parsed, prefix checked key-by-key);BTreeMapper write — fixed with an in-placesingle-key extension.
Gates
rubash: lib 581/581;
tests/array_store_parity.rs(42 GNU-verified cases) greenwith the store on and off;
cli_testsred-set andexecutor_testsfailure-setidentical to master
14209b9; 2500-seed differential fuzz branch==master0/2500 (bash-diff 677==677).
niubash (product;
niurebuilt against this branch vs master, same niubash):probes.shPASS=97 with an identical structural-diff set (4 pre-existing:mx-printf-fmt-var,mx-enable-f,mx-pushd,mx-set-c);interactive2.shconverges to the identical stable failure set (
hist-persist,repl-handoff,tab-file) withctrl-c-okflaky on both sides across runs. Element buildthrough the product shell: 10135 ms (master) → 124 ms (branch) for n=4000.
Oracle caveat: the reference here is GNU Bash 5.3.20 (this host), not the
repo's designated WSL 5.3.0; these Termux/Android figures are not Windows/Linux
x86_64 validation.
Still open
a+=(...)) and a mid-array overwrite (a[3]=x) stillre-render the whole mirror, so both remain O(n) per write; the structured cell
itself is now incremental. Phase 1c.
materialisation point at every whole-table consumer — a design of its own.
DATA_DQUOTEbyte leaking intoa+=("$v")) is filedseparately.
nor dropped.
perf(1b): amortise the indexed element write with the structured cell (…
caomengxuan666 commentedon Oct 15, 2026
Phase 1c is up: #632 (
perf/compound-append-in-place,557374d, on top of 1b37d6caf).The remaining quadratic write. 1b's "not addressed here" named it:
a+=(...)still re-parsed and re-rendered the whole mirror, so the loop idioma+=($i)was O(n²). Measured on untouched master:cmp20001985 ms,cmp40008175 ms — 4.12x for 2x the elements (quadratic), 50.9x / 190.1x GNU (39 / 43 ms).Cause.
append_array_valueopened withindexed_array_entries(current)(whole-mirror parse into aBTreeMap) and the caller then re-rendered and re-synced the cell — three O(n) passes per element appended. The parse is memoised and each render feeds it back, so master's is a hit; it is stillas_ref().clone()of the whole map. GNU edits theARRAYobject in place (assign_compound_array_list,arrayfunc.c:700;last_ind = array_max_index(a) + 1,arrayfunc.c:743;array_insert,array.c:516) and never re-serialises — and thatARRAYobject is rubash's structured cell.Fix. Seed the decode from the structured cell (the 1a "complete or absent" invariant that 1b already relies on) and hold this call's writes in a small mutations map, so no element map is built; then grow the canonical mirror by exactly the renderer's segments (
append_indexed_mirror_segments, 1b's helper generalised to a segment list) and extend the cell. Every other shape — an overwrite at or below the old max, an integer array, no cell, a non-canonical mirror, readonly — falls back to the unchanged render path.Measured (order-rotated best-of-9, release, same tree, bash 5.3.20):
cmp2000cmp4000cmp_literal2000elem2000_ctl(1b control)No row regresses and the 1b control is unchanged. The shape is the point: master 1985 → 8175 ms for 2x the elements (4.12x, quadratic), branch 68 → 95 ms (1.40x, ~linear).
cmp2000is now 1.7x GNU instead of 50.9x.Gates. lib 584/584;
array_store_parity(54 GNU-verified cases, +12 for 1c) green on and off;cli_tests0 new failures andexecutor_tests0 new failures vs master; 52-case whole-class differential matrix 0branch != master; 2500-seed fuzzbranch != master0/2500 withbash != branch==bash != master.Measurement note worth keeping: this suite must be compared serially. At
--test-threads=4executor_testsraces on shared paths undertarget/(e.g.target/rubash-lineno-assignment-output.txt: No such file or directory) and reported 2 phantomcli_tests"regressions" plus 4 new / 6 disappearedexecutor_testsrows — every one passes in isolation and none is related to this change.Filed separately while building the 1c matrix: #631 — a compound assignment with an out-of-range negative subscript (
a=(); a+=([-1]=x)) is silently dropped where GNU reportsbad array subscript(arrayfunc.c:801-809) and exits 1. Pre-existing on master, unrelated to the store; kept out of this perf PR so it stays one concern.Durable write-up:
docs/perf-issue-616-array-store.md.perf(1c): grow the compound append in place from the structured cell (#…
caomengxuan666 commentedon Oct 16, 2026
Follow-up after syncing current master 12da0b5 (Niubash6295367): the previously reported PR627 unset-all regression is STILL reproducible in the latest product build.
Using the original script file target/issue359/pr627-probe.sh: initialize three indexed elements; unset a[@]; print length; repeat with a[*].
RUBASH_ARRAY_STORE=1: stdout 3 then 3, rc0, empty stderr.
RUBASH_ARRAY_STORE=0: stdout 0 then 0, rc0, empty stderr.
Designated GNU5.3.0 had already returned 0 then 0 for this same script in the original review. Current unset_arrays.rs flush branch still updates env_vars and returns without synchronizing the typed cell.
The existing array_store_parity (2 harness tests) and issue631 regression (9 tests) both pass, so those suites do not cover this omission. This is an outstanding correctness blocker, not an integration/text conflict; please do not treat phase1a/1b/1c merges or their benchmarks as proving all write routes correct.
caomengxuan666 commentedon Oct 16, 2026
Perf phase is up as PR #652.
Key-count sweep, N=20000
a[i%K]=$i, min-of-3 order-rotated, release:Two things the recon paid for: (1) the battery caught a live sparse-compound dense-cell bug on master (
a=([5]=x [2]=y); a[2]=zduplicated) — fixed in-PR as the cell-trust precondition; the unset-flush sibling is #651, not bundled. (2) indexed readers fold by construction, so no parse/render changes — only the two verbatim printers needed a fold-before-print.perf(executor): append indexed overwrite writes instead of re-renderi…
caomengxuan666 commentedon Oct 16, 2026
Landed as #652 (squash-merged bc258ad). Indexed overwrite curve is flat: K=5000 177x vs master, GNU gap 674x -> 3.8x. Precondition fix included (declare-seeded dense cells); unset-flush sibling tracked in #651.
docs(readme): overhaul — Performance section with pinned numbers, hon…
caomengxuan666 commentedon Oct 22, 2026
Re-measured on niubash 1.4.4 / Termux aarch64: indexed writes 2k at 2.26x,
${#arr[@]}on 5k at 2.14x; scaling append 2500/5000/10000 gives ~1.6x per doubling in BOTH shells (= linear). Steady ~2.1-2.3x overhead remains but no n^2 signature at these sizes — may be fixed or size-dependent.