Skip to content

[perf][P1] Arithmetic-for / loop execution 2.37x slower than GNU bash: per-eval state ticket, lvalue+read+write allocations, CommandNode rebuild, per-command probes #607

Closed

Description

@caomengxuan666

Evidence

Android/Termux aarch64 (6-core tablet), niubash 1.4.0 Android build (embeds rubash e785c3c8f610, same commit as this checkout) vs GNU bash 5.3.20-1 aarch64. Interleaved runs, best-of-3, same script files for both shells. Bench scripts: bench_niu/ (in the umbrella benchmark issue).

script bash rubash/niu ratio
for ((i=0; i<200000; i++)); do :; done 0.572s (2.86 µs/iter) 1.353s (6.77 µs/iter) 2.37x
x=0; for ((i=0; i<100000; i++)); do x=$((x*3+7)); done 0.349s (3.49 µs/iter) 0.788s (7.88 µs/iter) 2.26x

The engine itself is not slow to boot (rubash -c true from this checkout measures 6-11ms vs bash 8ms — see unixwin/niubash#351 for where niu pays its extra ~14ms). The gap is pure per-iteration execution cost: ~4 µs/iteration of avoidable work. Parsing happens once (no re-tokenize per iteration), so everything below is on the execution side.

Root cause (all citations verified against this checkout)

1. Fixed "ticket" cost of every arithmetic evaluation (~0.4-0.7 µs/iter)

eval_arithmetic_command_value_with_flags (src/executor/arithmetic/mod.rs:324-479) pays, on every evaluation (test + update = 2x/iteration, 400k times in the first benchmark):

  • two keyed env_vars.remove() calls: __RUBASH_ARITH_SUBSCRIPT_EXPR (mod.rs:336-341) and __RUBASH_ARITH_EXP_EXPANDED (mod.rs:463-465, with a conditional insert at mod.rs:441-445) — String-keyed HashMap delete/insert even when no assoc-subscript expansion ever ran;
  • shopt::option_enabled("array_expand_once") (mod.rs:348-352) + set::shell_option_enabled("nounset") (mod.rs:~382) — two option-table lookups per eval;
  • arithmetic_preexpansion_is_identity(expression.as_bytes()) (mod.rs:364) — full-string byte scan (the fast admission itself, rubash#156 — fine, but it runs after the state resets above);
  • ARITH_WRITES.clear() (mod.rs:447) + arith_dynamic_context() (mod.rs:450) which calls bashpid_value() → std::process::id() (src/executor/dynamic_arrays.rs:621-622, a real getpid syscall on glibc ≥2.25 and bionic) and clones debug_trap_command (dynamic_arrays.rs:375);
  • sync_arith_writes_to_shell_state(self) (mod.rs:478) — consumes the write log: per write one env_vars.get + old/new compare + shell_state.variables BTreeMap update with a value clone (mod.rs:82-100). The evaluator writes env_vars while parameter lookup prefers the typed store, so every evaluation boundary pays a diff-sync (the rubash#404 comment at mod.rs:66-77 documents this structural split).

For i<200000 / i++ — three tokens — none of this state is ever live.

2. Every lvalue parse allocates a HashSet + String (src/executor/arithmetic/lvalue.rs:201-219)

pub(super) fn resolved_lvalue_name(&self, name: &str) -> String {
    let mut current = name;
    let mut seen = HashSet::new();          // fresh HashSet per lvalue
    for _ in 0..16 {
        if !seen.insert(current.to_string()) { ... }   // String alloc + hash
        if !is_marked_var(self.env_vars, NAMEREF_VARS, current) {
            return current.to_string();     // alloc even for the non-nameref case

Called once for the test expression and once for the update expression each iteration. In ~all real loops the first is_marked_var check is false — the loop, the HashSet, and the String exist only for nameref chains that never happen. The allocation-free move: check the NAMEREF mark on the borrowed &str first; only start the cycle-guard machinery when a hop actually occurs.

3. Every arithmetic variable read clones the value (src/executor/arithmetic/value.rs:348-354)

let value = self.env_vars.get(name).cloned()
    .or_else(|| std::env::var(name).ok()).unwrap_or_default();
self.evaluate_variable_text(name, &value)

evaluate_variable_text only trim()s and parse::<i128>()s — a &str would do. One heap alloc + memcpy per variable read (1-2/iteration here), preceded by is_marked_var(UNSET_DYNAMIC_VARS, ...) and the dynamic-parameter probe chain.

4. Every arithmetic variable write is a multi-alloc, two-store operation (src/executor/arithmetic/value.rs:552-600+)

set_variable per write: bash_arith(value).to_string() (value.rs:555), NAMEREF mark lookup + .cloned() cell reads (value.rs:591-600), insert(name.to_string(), value.clone()) — plus record_arith_write(name, old_value) pushing (name.to_string(), old_value) into the thread-local log (mod.rs:55-59), which sync_arith_writes_to_shell_state then replays against the BTreeMap (mod.rs:82-100). ~6-7 allocations + 2 map stores + a diff per assigned variable. GNU does bind_variable: one hash hit, in-place write (no second store, no replay log).

5. The loop body rebuilds the whole command node per iteration (src/executor/command_prepare.rs:921-1036)

expand_command_words constructs a fresh CommandNode cloning ~30 fields (word_metadata, assignments, redirects, redirect_in/out, heredoc*, pipe, braces… — nodes.rs:1306-1363 puts the struct at ~900 B with 28 Vecs), then collects expanded_words: Vec<(String,bool)> and a second words Vec — for :, a literal-only command with nothing to expand. ~0.6-1.0 µs/iteration of struct construction/destruction + 3-4 heap allocs.

6. Per-command fixed probe chain (src/executor/ast_exec.rs)

Every command execution runs:

  • DEBUG-trap lookups: has_active_trap_action(env_vars, "DEBUG", ...) — 2 env gets (ast_exec.rs:515-519);
  • five sequential dispatch probes — execute_time_prefixed_command_sequence, execute_simple_if, execute_simple_loop, execute_pipe_into_source, execute_alias_escaped_pipe (ast_exec.rs:591-635) — each re-inspecting static node properties;
  • run_pending_signal_traps → take_pending_signals(std::process::id()) (trap_exec.rs:950) plus the subshell guard std::process::id() at trap_exec.rs:934 — two getpid syscalls per command.

These probes recompute what is statically known per AST node (is it time-prefixed / an if / a loop — fixed at parse time).

7. Loop-entry deep copies (once per loop; O(body × nesting))

execute_for_command_with_redirects clones the whole cmd and the whole for_command including body (src/executor/loop_select.rs:261-267); the arithmetic-for path then clones the body again into a new Ast (src/executor/compound_exec.rs:1161-1163, body.to_vec()). The literal-for path already avoids this via execute_ast_inner(&for_command.body) (loop_select.rs:226) — the two paths are inconsistent. Small for a 1-command body, O(N·L) for nested/large bodies.

8. Arithmetic expression text re-parsed on every evaluation (src/executor/arithmetic/parser.rs:2382-2396)

A fresh ConditionalArithParser (with fresh resolving: Vec, diags: Vec) is built per evaluation. GNU also re-evaluates the text per eval (evalexp), so this alone is roughly parity — but rubash's parse-time work (ArithmeticExpressionMetadata, nodes.rs:177-186, produced during the one-time parse) is never consumed by the executor, so nothing amortizes.

Estimated per-iteration budget (static attribution, sums to the observed ~6.8 µs)

item est.
2x arithmetic ticket + sync (§1) 0.8-1.2 µs
test/update lvalue HashSet+String (§2) 0.6-1.0 µs
variable read clone (§3) 0.2-0.4 µs
i++/x= write chain + dual-store sync (§4) 0.8-1.2 µs
CommandNode rebuild for : (§5) 0.6-1.0 µs
probe chain + getpid (§6) 0.3-0.6 µs
loop framework (reap/xtrace/debug probes) 0.2-0.4 µs
already-optimal baseline (parse-once, eval loop) ~2.5 µs

Fix directions (root-cause subsystems, in ROI order)

  1. Gate the arith ticket on what actually ran (§1): do the SUBSCRIPT_EXPR/EXP_EXPANDED removes only when the assoc/expanded passes ran (the preexpansion_is_identity flag computed at mod.rs:364 already proves they didn't), cache bashpid in a Cell (depth-0 value is process-constant), keep option lookups (array_expand_once, nounset) in per-eval lazy state instead of two map hits. Pure state-reset removal — no semantic surface.
  2. Allocation-free lvalue fast path (§2): NAMEREF-mark check on the borrowed name first; HashSet/String only when a hop occurs.
  3. Borrowed variable reads (§3): return &str/Cow from the evaluator's variable lookup; trim/parse in place.
  4. Writer path: entry API for the final insert, skip the record_arith_write replay when the diff-sync has nothing to replay (§4), and — the structural fix — converge the evaluator onto one store (GNU bind_variable semantics), removing sync_arith_writes_to_shell_state from the hot boundary entirely (matches the AGENTS.md "fix the wrong invariant" rule rather than memoizing the symptom).
  5. Zero-copy loop bodies (§5, §7): literal-only commands (: with no expansions, no assignments, no redirects) skip the CommandNode rebuild; both for-loops use execute_ast_inner(&body) (already exists at loop_select.rs:226); drop cmd.clone()/for_command.clone()/body.to_vec().
  6. Parse-time probe bitmask (§6): precompute time-prefix/simple-if/simple-loop/pipe-source/alias-pipe as static per-node flags at parse time; cache DEBUG-trap activity behind a generation counter; cache std::process::id() once per process (subshells are fresh processes, so a process-constant cache is safe).

Impact

Arithmetic/loop-heavy scripts are a core bash workload (awk-less one-liners, seq-replacement loops, generated build scripts): currently 2.3-2.4x slower than GNU. Items §5-§6 tax every command executed, not only loops, so fixing them lifts interactive script latency across the board. Estimated ceiling: closing §1-§4 + §6 alone accounts for ~3.5-5 µs of the observed ~4 µs overhead per iteration.

Verification plan

  • Rebuild locally (cargo build --release — 3m06s on this Android aarch64 device), re-run bench_niu/ scripts; target ≤1.3x vs bash on both microbenchmarks.
  • No semantic change: every fix above either removes dead state resets or replaces allocation with borrowing — still, run the WSL GNU Bash 5.3.0 true-baseline suite per AGENTS.md before merge; arithmetic-write visibility (rubash#404 class) is the risk surface for item 4, so the [[ -eq ]] / let / subscript sync probes must be in the focused set.

Related

  • unixwin/niubash#352 — umbrella benchmark matrix for this device (environment, methodology, full results)
  • unixwin/niubash#351 — startup cost is wrapper-side; local rubash -c true measures at bash parity, so none of the numbers above include a startup penalty from the engine

Activity

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

    @caomengxuan666
    MemberAuthor

    已认领并完成初步 triage。当前 D:/repo/rubash checkout 含他人未跟踪文件(.158.part, .claude/, output/ 等),按仓库协作规则我不会在该工作树上编辑、清理或重置;因此本 issue 暂不能安全落 patch。根因方向已确认在 assignment hot path,需要在干净 worktree 按 GNU source/83-suite 要求处理。

  3. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    已落地低风险优化:算术 lvalue/nameref 路径先借用名称并在确实命中 nameref 时分配,普通变量跳过 HashSet/String 分配;cargo check --locked 与格式检查通过。变量双存储架构未改。

  4. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Reopen: PR#611 delivered a real but partial win — arithmetic loops now match GNU, but the function-call path (this issue's other root cause) is untouched and still 10.8× slower

    Measured on-device after rebuilding from master 334afab (engine-only rubash, best-of-3 wall, vs the archived 1.4.0 engine at e785c3c and GNU bash 5.3.20):

    workload rubash e785 (1.4.0) rubash 334afab (new) GNU bash new vs bash
    arithmetic loop ×200k 1 290 ms 1 176 ms 1 175 ms 1.00× — parity ✅
    fib(20) recursion 3 261 ms 3 411 ms 315 ms 10.8× slower ❌

    Credit where due: the lvalue.rs + variable_state.rs changes closed the arithmetic-loop gap entirely (this issue's headline case). But the same root-cause list contained the function-call machinery, and none of it was touched by #611:

    Closing this issue hides ~4 documented root causes behind a fixed headline case. Reopening to request a follow-up PR scoped to the function-call/loop machinery, with fib(20) as the acceptance benchmark (target: within ~1.5× of bash, currently 10.8×). The allocation counters above are a noise-free regression gate for it.

    Also: fib measured 0.96× old→new (3 261→3 411 ms, i.e. no change / possible small regression — within best-of-3 noise, but nothing landed for this path).

  5. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Profiling evidence for the 2.37× arithmetic/loop gap — allocation + syscall profiles

    Follow-up measurements from the Android benchmark campaign (tools described in unixwin/niubash#352's profiling appendix). Two findings that both confirm this issue's root-cause direction and add one concrete new lead:

    1. The arithmetic loop is NOT allocation-volume-bound — it's CPU-side per-eval work

    LD_PRELOAD allocator interposer, x=0; for ((i=0;i<200000;i++)); do x=$((x*3+7)); done:

    shell malloc realloc bytes
    bash 5.3 8 000 707 1 197 MB
    niu 1.4.0 7 602 432 1 000 183 222 MB

    niu does fewer mallocs than bash for the same loop yet is 2.37× slower in wall time — consistent with this issue's analysis (per-eval ticket/env sync/diff-store/getpid/option lookups are CPU work, not allocation volume). Syscall profile (strace -f -c) is also flat: the 200k-iteration loop adds ~40 syscalls in both shells (1 162 vs 3 115 total, all baseline runtime noise) — the gap is 100% interpreter-side CPU, as diagnosed here.

    2. New lead: exactly ~5 reallocs per arithmetic-loop iteration

    niu performs 1 000 183 reallocs for 200 000 iterations (~5/iteration; bash: 1 realloc for the entire run). A per-eval growable buffer that reallocs instead of amortizing is a cheap, measurable target inside the same fix series — worth checking alongside the ticket/diff-store work (a doubling-growth buffer should show ~log₂(iterations) reallocs, not 5/iteration).

    3. Function-call path: 9× allocations, 36× bytes (recursion)

    fib(){ if (( $1 < 2 )); then echo $1; else fib $(($1-1)); fib $(($1-2)); fi; }; fib 20 >/dev/null:

    shell malloc realloc bytes
    bash 5.3 2 183 372 3 54.3 MB
    niu 1.4.0 19 759 188 1 959 479 1 939 MB

    ~97 KB of allocator traffic per function call in niu vs ~25 KB in bash — the function-call/parameter-passing path is the single worst allocator offender measured, corroborating the CommandNode-rebuild and per-call state-allocation claims here. A fib 20 under the interposer is a ready-made regression microbenchmark for the fix series (LD_PRELOAD=libprof.so counts are stable run-to-run).

    Methodology one-liner: bench_niu/prof.c (bionic-safe malloc/free/realloc/calloc + pthread_mutex interposer, totals at exit via atexit), single run per cell, counters deterministic (<1% drift across spot-check runs). Mutex contention was also instrumented: 0 contended locks in every workload in both shells — ruling out lock contention as a contributor.

  6. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Measurement correction: the table in my reopen comment ran under background load — arith did not reach parity (quiet numbers: 1.63× bash); the demand stands, firmer

    Disclosure: that table was measured while a cargo test suite was hammering the same 6 cores. The old→new columns (both binaries sampled back-to-back) were load-immune — the bash column was not (bash arith read 1 175 ms under load; idle now it is 653 ms). Quiet re-measure, best-of-3, nothing else running:

    workload rubash e785 rubash 334afab (new) niu product (82fbbe1+334afab) GNU bash new engine vs bash
    arith ×200k 1 166 ms 1 062 ms 1 443 ms 653 ms 1.63×
    fib(20) 1 771 ms 1 790 ms 1 970 ms 202 ms 8.86×

    Corrections to the reopen comment above:

    • "1.00× — parity ✅" → perf(1.4.1): reduce parameter and nameref allocation overhead #611's real gain on the headline arithmetic case is 1.09× (1 166→1 062); the gap vs GNU is 1.63×, not closed. The original root causes beyond lvalue.rs (per-eval ticket, dual-store diff-sync, loop-entry copies, per-command probes) remain.
    • fib is 8.86× (I quoted 10.8×), old→new 0.99× — still zero movement on the function-call path, exactly as stated.
    • The product niu sits another +36% above the engine (1 443 vs 1 062), linear in loop count (100k→200k scales exactly 2×, intercept ≈ startup) → a per-command wrapper cost in niubash-runtime, cross-tracked on niubash#349.
    • The clean ratios also re-align with this issue's original baseline (original report: niu arith 2.37×; quiet today: 2.21× ✓).

    Allocation/syscall counters in the profiling appendix below are single-run interposer counts — unaffected by this correction. Reopen scope and acceptance benchmark unchanged (fib within ~1.5× of bash; arith to true parity ≤1.1×).

  7. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    First cut is up as PR #665 (branch perf/issue607-literal-dispatch on e571267): whitelist skip of the word-expansion rebuild for literal single-word commands. Rotated min-of-5: : 2.03x->1.77x, true 1.86x->1.67x (~0.7us/iter). Shared preserve predicate (never duplicated), GNU cites in code (execute_cmd.c:4468, subst.c:13219), contract test pins fast==pipeline per word. This lands the dispatch-rebuild third of the gap; arith ticket + loop machinery remain.

  8. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    First cut landed as #665 (squash-merged 73fbbf6). : 2.03x->1.77x, true 1.86x->1.67x. Issue stays open for the arith-ticket gating and loop-machinery residuals.

  9. added a commit that references this issue on Oct 16, 2026
  10. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Second cut up as PR #671 (branch perf/issue607-arith-ticket): two-gate whitelist skipping the per-eval ticket (shopt/nounset/marker/context/sync) for read-only identity shapes. Dense probe ~5% (~200ns/eval); headline loop unchanged. 6 contract tests incl. fast==slow parity. Gate running.

  11. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Second cut landed as #671 (squash-merged 2753e4b): two-gate whitelist skipping the per-eval ticket for read-only identity shapes (~5% on dense probes; headline loop unchanged). Gates identical (niu 49=49). Remaining: loop-machinery half (body_ast rebuild, timers, traps) — follows the compound slice.

  12. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Third cut up as PR #679 (branch perf/issue607-loop-machinery): body by pointer (no per-entry Ast clone/wrapper), DEBUG probe gating with post-body re-probe, empty-table reap skip. N=200k : loop -3.4% (~250ns/iter). 6 contract tests; upstream scripts byte-identical. Gate running.

  13. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    All three cuts landed with green gates: #665 literal dispatch (: 2.03x->1.77x, ~0.7us/iter), #671 arith ticket (dense ~5%), #679 loop machinery (-3.4%). Combined :-loop thermals moved with each slice; current load on this box voids a fresh combined number, so no new claim here. Residual is the shape-independent per-command floor (~2.8us, shared with all constructs) — future work, new issue if pursued.

  14. caomengxuan666 commented on Oct 22, 2026

    @caomengxuan666
    MemberAuthor

    Re-measured on niubash 1.4.4 / Termux aarch64 (median of runs, same machine): ((s+=i)) 20k is now 120ms vs GNU 90ms (1.33x), $((s+i)) 20k is 152 vs 104ms (1.46x) — well below the 2.37x in the title. If the listed root causes were addressed, this may be closable or retitlable.

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