Repository navigation
Description
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 conditionalinsertatmod.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 callsbashpid_value()→std::process::id()(src/executor/dynamic_arrays.rs:621-622, a realgetpidsyscall on glibc ≥2.25 and bionic) and clonesdebug_trap_command(dynamic_arrays.rs:375);sync_arith_writes_to_shell_state(self)(mod.rs:478) — consumes the write log: per write oneenv_vars.get+ old/new compare +shell_state.variablesBTreeMap update with a value clone (mod.rs:82-100). The evaluator writesenv_varswhile parameter lookup prefers the typed store, so every evaluation boundary pays a diff-sync (therubash#404comment atmod.rs:66-77documents 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 caseCalled 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 guardstd::process::id()attrap_exec.rs:934— twogetpidsyscalls 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)
- Gate the arith ticket on what actually ran (§1): do the
SUBSCRIPT_EXPR/EXP_EXPANDEDremoves only when the assoc/expanded passes ran (thepreexpansion_is_identityflag computed atmod.rs:364already proves they didn't), cachebashpidin aCell(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. - Allocation-free lvalue fast path (§2): NAMEREF-mark check on the borrowed name first;
HashSet/Stringonly when a hop occurs. - Borrowed variable reads (§3): return
&str/Cowfrom the evaluator's variable lookup;trim/parsein place. - Writer path:
entryAPI for the final insert, skip therecord_arith_writereplay when the diff-sync has nothing to replay (§4), and — the structural fix — converge the evaluator onto one store (GNUbind_variablesemantics), removingsync_arith_writes_to_shell_statefrom the hot boundary entirely (matches the AGENTS.md "fix the wrong invariant" rule rather than memoizing the symptom). - Zero-copy loop bodies (§5, §7): literal-only commands (
:with no expansions, no assignments, no redirects) skip theCommandNoderebuild; both for-loops useexecute_ast_inner(&body)(already exists atloop_select.rs:226); dropcmd.clone()/for_command.clone()/body.to_vec(). - 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-runbench_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#404class) 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; localrubash -c truemeasures at bash parity, so none of the numbers above include a startup penalty from the engine
Activity
caomengxuan666 commentedon Oct 15, 2026
已认领并完成初步 triage。当前
D:/repo/rubashcheckout 含他人未跟踪文件(.158.part,.claude/,output/等),按仓库协作规则我不会在该工作树上编辑、清理或重置;因此本 issue 暂不能安全落 patch。根因方向已确认在 assignment hot path,需要在干净 worktree 按 GNU source/83-suite 要求处理。caomengxuan666 commentedon Oct 15, 2026
已落地低风险优化:算术 lvalue/nameref 路径先借用名称并在确实命中 nameref 时分配,普通变量跳过 HashSet/String 分配;
cargo check --locked与格式检查通过。变量双存储架构未改。caomengxuan666 commentedon Oct 15, 2026
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):Credit where due: the
lvalue.rs+variable_state.rschanges 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:command_prepare.rs:921-1036) — fib(20) does ~13k calls; niu allocates 9.0× bash's malloc count and 36× its bytes for the same recursion (19.76M allocs / 1 939 MB vs bash 2.18M / 54 MB, LD_PRELOAD interposer, numbers in [perf][P2] Android aarch64 v1.4.0 vs GNU bash 5.3 benchmark matrix: interpreter-bound 2.3-7.3x slower, fork-bound 1.8-5.2x faster, startup +14ms (wrapper #351), RSS 2.2x — root causes filed as rubash#607-609 niubash#352's profiling appendix);ast_exec.rs:515-519,591-635,trap_exec.rs:934,950);loop_select.rs:261-267,compound_exec.rs:1161-1163);mod.rs:82-100).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).
caomengxuan666 commentedon Oct 15, 2026
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_PRELOADallocator interposer,x=0; for ((i=0;i<200000;i++)); do x=$((x*3+7)); done: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:~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 20under the interposer is a ready-made regression microbenchmark for the fix series (LD_PRELOAD=libprof.socounts 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.caomengxuan666 commentedon Oct 15, 2026
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 testsuite 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: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 beyondlvalue.rs(per-eval ticket, dual-store diff-sync, loop-entry copies, per-command probes) remain.niusits 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 inniubash-runtime, cross-tracked on niubash#349.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×).
caomengxuan666 commentedon Oct 16, 2026
First cut is up as PR #665 (branch
perf/issue607-literal-dispatchone571267): whitelist skip of the word-expansion rebuild for literal single-word commands. Rotated min-of-5::2.03x->1.77x,true1.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.perf(executor): skip word-expansion rebuild for literal commands (#607)…
caomengxuan666 commentedon Oct 16, 2026
First cut landed as #665 (squash-merged 73fbbf6).
:2.03x->1.77x,true1.86x->1.67x. Issue stays open for the arith-ticket gating and loop-machinery residuals.docs: changelog + perf ledger land #607 first cut and #608 (#665/#666)
caomengxuan666 commentedon Oct 16, 2026
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.perf(executor): skip the per-eval arith ticket for read-only shapes (#…
caomengxuan666 commentedon Oct 16, 2026
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.
caomengxuan666 commentedon Oct 16, 2026
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.perf(executor): arith-for loop machinery without per-iter rebuild (#607…
caomengxuan666 commentedon Oct 16, 2026
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.docs: close out #607/#609/#619 lanes in ledger + changelog
docs(readme): overhaul — Performance section with pinned numbers, hon…
caomengxuan666 commentedon Oct 22, 2026
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.