Skip to content

[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

Closed

Description

@caomengxuan666

Result summary

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

Activity

  1. added
    P1-high
    performance
    on Oct 15, 2026
  2. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    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.
    • Assoc write 17x ([perf][P1] Associative-array write m[$k]=v is 16.7× slower (73µs/op vs 4.3µs, 100 keys) — same store/diff-sync family as #616 #618) — same string storage, plus assoc_hash_ordered_values re-deriving the hash order (arrays/executor.rs assoc_subscript_range_values) per op.

    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.

  3. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    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).

    Readers (parse the storage string per call)

    reader location cost used by
    array_values(&str) -> Vec<String> arrays/storage.rs:16 O(n), uncached array_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 O(n) but string-keyed memoized (_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/914
    dynamic views (PIPESTATUS, BASH_LINENO, …) dynamic_arrays.rs:526-573 computed view, no storage 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
    declare -a/compound assign builtins/declare/assign.rs:278-853, setattr/value.rs:96 re-render per assignment
    assoc element assign array_assignment_exec.rs:356-359 (format_assoc_storage) A[k]=v: full hash re-render per write → #618's 17×

    Hot-path vs cosmetic

    • Hot: ${#a[@]} (array_length → array_values().len() — uncached O(n) per call, unlike indexed_array_entries), a[i]= build (O(n²)), "${a[@]}" iterate (O(n) inherent — fine), A[k]=v build.
    • Cosmetic: declare -p / @A render (rare).

    Target model (GNU reference, third_party/bash/)

    • 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)

    1. 1a typed storage behind parameter_array_storage accessor + render fallback (no behavior change, gates must stay identical);
    2. 1b ${#a[@]} O(1) via maintained count (kills the per-call array_values().len());
    3. 1c element assignment in-place / amortized (kills O(n²) build — [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);
    4. 1d assoc typed map (kills [perf][P1] Associative-array write m[$k]=v is 16.7× slower (73µs/op vs 4.3µs, 100 keys) — same store/diff-sync family as #616 #618's per-write re-render);
    5. 1e delete the string round-trip for remaining hot readers; keep render only for declare -p/@A.
  4. added a commit that references this issue on Oct 15, 2026
  5. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Phase 1a — PR #627 (open, CI green)

    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:121 array_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.
    • Write-up: 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 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 complete IndexedArray, the mirror is a
    canonical STORAGE_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.

  6. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    #616 status: Phase 1a merged, Phase 1b in review

    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).

    Measured (order-rotated best-of-5, Termux/Android aarch64, release)

    Workload bash master branch master/branch
    ${#s} scalar control (200k) 540 1842 1751 1.1x
    build10k compound + ${#a[@]} 30 64 52 1.2x
    sparse + 200k ${#a[@]} 582 1875 1610 1.2x
    element build n=2000 31 1760 51 34.5x
    element build n=10000 56 46071 157 293.4x
    compound append n=2000 29 1898 1915 1.0x
    element build + iterate n=2000 36 1930 64 30.2x
    b=("${a[@]}") ×2000, n=2000 5554 21843 22086 1.0x
    element write + ${#a[@]}, n=5000 42 23199 9890 2.3x

    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
    master NA (>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.sh PASS=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

  7. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    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=4 executor_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.

    Durable write-up: docs/perf-issue-616-array-store.md.

  8. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    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.

  9. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Perf phase is up as PR #652.

    Key-count sweep, N=20000 a[i%K]=$i, min-of-3 order-rotated, release:

    keys master/write branch/write master/GNU branch/GNU
    100 101.10us 20.85us 21.51x 4.44x
    1000 889.55us 20.45us 172.73x 3.97x
    5000 3638.45us 20.60us 673.79x 3.81x

    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.

  10. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    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.

  11. caomengxuan666 commented on Oct 22, 2026

    @caomengxuan666
    MemberAuthor

    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.

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

Metadata

Metadata

Labels

P1-highperformance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions