Repository navigation
Description
Evidence
Android/Termux aarch64 (6-core tablet), niubash 1.4.0 Android build (embeds rubash e785c3c8f610) vs GNU bash 5.3.20-1 aarch64. Interleaved, best-of-3.
Pure assignment microbenchmark (30k iterations):
S=abcdefghijklmnopqrstuvwxyz
for ((i=0; i<30000; i++)); do t=$S; donebash 0.086s vs niu 0.234s → 2.72x. The empty-loop baseline for the same shell pair extrapolates to ~0.086s (bash) / ~0.203s (niu), i.e. bash's assignment here rounds to noise while niu adds ~0.031s (~1 µs/assignment) of pure assignment machinery. The x=$((x*3+7)) arm of the arithmetic-for benchmark (2.26x, see that issue) pays this same path on top of the evaluator costs.
Root cause (all citations verified against this checkout)
1. Every scalar assignment inserts into assignment_expansion_memo, which is only ever read under xtrace
src/executor/temporary_assignments.rs:29-32:
let expanded_value = self.expand_assignment_value_with_raw(name, value, raw);
self.assignment_expansion_memo
.borrow_mut()
.insert((name.clone(), value.clone()), expanded_value.clone()); // 3 String clones + hash insertThis runs unconditionally on every assignment. The memo's only reader is xtrace_assignment_text (src/executor/prompt_expansion.rs:961, sole caller xtrace_command_lines at prompt_expansion.rs:838, which is itself gated by if self.xtrace_enabled() at command_dispatch.rs:112 / command_prepare.rs:2952). The memo exists for rubash#254 (args=$(echo hi) echo x ran the RHS twice when tracing) — correct behavior, but the write is paid by 100% of assignments to serve the ~0% that have set -x on, and it is thrown away one command later anyway (command_execute.rs:35 clears it per command).
Fix shape: populate lazily from the xtrace path (the expansion it needs is recomputable there), or keep the memo only while xtrace_enabled() — a runtime flag gate, not a symptom blacklist.
2. Every scalar assignment writes two stores, with clones on both sides
src/executor/temporary_assignments.rs:1233-1245 (typed store) and :1265-1272 (env mirror):
if let Some(variable) = self.shell_state.variables.get_mut(base_name) { // BTreeMap lookup
if let ShellValue::Scalar(current) = &mut variable.value { *current = value.clone(); }
} else {
let _ = self.shell_state.variables.set_scalar(base_name, value.clone()); // alloc + insert
}
...
self.shell_state.env_vars.insert(base_name.to_string(), value.clone()); // alloc + insert
if crate::builtins::set::shell_option_enabled(&self.shell_state.env_vars, "allexport") { ... } // option lookup
sync_shell_assignment_process_env(&self.shell_state.env_vars, base_name, value); // setenv path- The two stores are structural:
shell_state.variables: BTreeMap<String, Variable>(src/shell/variables.rs:43) — lookups are O(log n) string comparisons over ~170 entries — plusenv_vars: HashMap<String, String>as the export/attribute mirror. - The same split is what forces the evaluator-side replay log (
record_arith_write→sync_arith_writes_to_shell_state,src/executor/arithmetic/mod.rs:55-59,:82-100— see the arithmetic-for issue §1/§4): every variable mutation in the engine is written twice and diff-synced once. Therubash#404comment atmod.rs:66-77documents the invariant that makes this necessary today: the evaluator writesenv_varswhile parameter lookup prefers the typed store. - Per assignment: ≥2 value clones + 1 key clone + 1 BTreeMap op + 1 HashMap op + 1 option lookup + the process-env sync.
GNU's model (variables.c): one bind_variable into a single hash table, value moved once, exported flag carried on the cell — no mirror, no replay, no diff.
3. Nameref pre-resolution allocates before checking whether the variable is a nameref
src/executor/variable_state.rs:108-124:
pub(in crate::executor) fn nameref_resolution(&self, name: &str) -> NamerefResolution {
let mut current = name.to_string(); // heap String per call
for level in 1..=9 {
if !is_marked_var(&self.shell_state.env_vars, NAMEREF_VARS, ¤t) {
return if current == name { NotNameref } else { Target(current) };Callers include the general assignment path (temporary_assignments.rs:649, :179), array assignment, loop variable resolution (loop_select.rs:197) and more — every one pays a String allocation for the overwhelmingly common verdict NotNameref (first is_marked_var check false, current == name). The name is already a &str for the entire non-hopping case.
Fix directions
- §1 — gate the memo insert on
xtrace_enabled()(one option-table read already cached elsewhere) or move population to the xtrace read site. Removes 3 allocations + 1 hash insert per assignment; zero behavioral surface when tracing is off (the memo is cleared unread anyway). - §2 (structural, the real fix) — converge on one authoritative store like GNU: either make
env_varsthe export mirror derived lazily at child-spawn/export time (it already serializes viaexport_environment), or make the typed store a view overenv_varswith attribute side-tables. This deletes the per-assignment double write, the evaluator replay log, and the sync boundary from every hot path at once — matches AGENTS.md "fix a wrong invariant / converge to the real mechanism" rather than caching around it. If a staged approach is preferred: movevariablesfromBTreeMaptoHashMap(checkdeclare -p/${!x}ordering consumers first) and skipset_scalarwhen the cell already holds the identical value (the sync layer already computes this comparison elsewhere). - §3 — check the NAMEREF mark on the borrowed
&strfirst; only allocate the workingStringwhen a hop actually happens (same shape as the arithmetic lvalue fix in the arithmetic-for issue §2).
Impact
- ~1 µs per scalar assignment of avoidable work; assignment-only loops measure 2.72x vs bash, and every
x=...in every script — including thex=$((...))arm of the arithmetic benchmark and thet=chains of the parameter-expansion benchmark — pays §1-§3. - §2 is shared infrastructure: fixing the two-store split also removes the evaluator's per-evaluation diff-sync, which is on the critical path of the arithmetic-for-loop gap (cross-ref).
Verification plan
- Local
cargo build --release+bench_niu/micro.sh(assignop) + the arithmetic-for benchmark; target: assign-op within 1.2x of bash, measurable knock-on improvement in both other issues' numbers. - Semantics risk is concentrated in §2 (export visibility,
allexport, readonly/nameref attribute handling,[[ -eq ]]sync — therubash#404class). Stage 1 (§1, §3) is allocation-only and safe behind the standard true-baseline slice; stage 2 (§2) needs the full 83-suite ledger per AGENTS.md, withexport/declare/nameref/readonlysuites called out.
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。当前 checkout 含他人未跟踪文件,按协作规则暂不直接编辑 rubash 工作树;标量赋值优化涉及 export/readonly/nameref 语义,需在干净 worktree 按 issue 验证计划实施。
caomengxuan666 commentedon Oct 15, 2026
已落地与 #607 共享的低风险 nameref lazy-allocation 优化:普通变量先返回 NotNameref,避免无意义 String 分配;未改双存储架构。相关检查通过。
caomengxuan666 commentedon Oct 15, 2026
Reopen: PR#611 fixed only the third root cause (nameref pre-allocation, +8%); the unconditional memo insert and the dual BTreeMap+HashMap stores — the two main costs — remain
Measured on-device after rebuilding from master 334afab (engine-only
rubash, best-of-3 wall, vs archived 1.4.0 engine at e785c3c and GNU bash 5.3.20):src/executor/variable_state.rs(nameref deferral) changed — that's the 8%. The two dominant root causes have zero lines changed in #611:temporary_assignments.rs:29-32; sole readerprompt_expansion.rs:961is gated byxtrace_enabled()— the memo can be gated the same way);temporary_assignments.rs:1233-1245,1265-1272,variables.rs:43).Allocator evidence (LD_PRELOAD interposer, unixwin/niubash#352 appendix): the assign loop still performs 1.27× bash's malloc count / 1.13× its bytes (8.40M / 151.3 MB vs 6.60M / 134.8 MB), i.e. the measurable allocation tail of the memo/dual-store path persists.
Reopening to request a follow-up PR gating the memo on xtrace and collapsing the dual stores, with the row above as the acceptance benchmark (target: within ~1.2× of bash, currently 2.2×). The allocator counters are deterministic and can gate the fix in CI.
caomengxuan666 commentedon Oct 15, 2026
Profiling evidence: scalar-assign loop allocates 1.27× the calls / 1.13× the bytes of GNU bash
LD_PRELOADallocator interposer (methodology: unixwin/niubash#352 profiling appendix), workloadfor ((i=0;i<200000;i++)); do v=$i; done:+1.8M allocations (+27%) and +16 MB (+13%) for the same loop — consistent with the unconditional per-assignment memo insert + dual-store write + nameref pre-allocation diagnosed in this issue. The multiplier is smaller than the 2.72× wall-time gap, i.e. roughly half the wall-time cost sits in the CPU-side state work (option lookups, diff-sync bookkeeping) rather than the allocation calls themselves — matching the issue's fix direction (make the memo xtrace-gated, collapse the dual stores).
caomengxuan666 commentedon Oct 15, 2026
Measurement correction: quiet re-measure — posted 2.2× corrects to 2.03×; conclusion unchanged
(Reopen table ran under background load; bash's wall column was inflated ~1.8×. Old→new columns were load-immune.) Quiet best-of-3:
temporary_assignments.rsmemo insert + dual stores have zero diff in perf(1.4.1): reduce parameter and nameref allocation overhead #611.niu: 1 551 ms = 2.83× GNU — matches this issue's original 2.72× baseline — and the wrapper adds +40% over the engine (1 551 vs 1 110, per-iteration), cross-tracked on niubash#349.Demand unchanged: gate the xtrace-only memo insert on
xtrace_enabled()+ collapse the dual BTreeMap/HashMap stores; acceptance row above, target ≤1.2× vs bash (alloc counters in the appendix are load-immune).caomengxuan666 commentedon Oct 15, 2026
重新认领后已完成 GNU subst.c:3576 do_assignment_internal 的 trace gate 核对,并在独立 worktree 实现 xtrace-only memo gating(permanent + temporary 两路径);Linux 两项新单元测试与现有 xtrace CLI 回归通过。release baseline / after 已分别构建,下一步提交实际交错 benchmark。该补丁不声称解决 dual-store 全部开销,未达 ≤1.2× GNU 的指标前不会关闭本 issue。
caomengxuan666 commentedon Oct 15, 2026
重要实测纠正:固定 scalar workload for ((i=0;i<200000;i++)); do v=$i; done 在当前 334afab 走 command_prepare 的 standalone assignment 路径,并不经过 apply_permanent_assignments 的 memo insert。Linux 2 warmup+9 rotating interleaved: baseline median1298.94ms / memo-gate1292.00ms / GNU350.94ms,变化仅0.5%且有离群样本;glibc分配计数约6.801M前后不变。因此不能把memo gating声称为这个scalar workload的性能修复。本 issue 保持开放,继续调查真正的state/store成本;bench脚本与完整样本将进后续PR。
caomengxuan666 commentedon Oct 15, 2026
后续 PR #620 已提交并通过全部必需 CI。实测 scalar allocation calls 6.802M -> 6.202M(-8.82%),但 wall median1323.35 ->1322.74ms基本持平;prefix453.56 ->448.76ms约-1.1%,GNU对应353.01/109.74ms。这是有bench证据的部分分配优化,不是完整性能验收;#609保持OPEN。完整命令、commits、9轮样本、输出一致性和未达标说明在 PR/docs。
perf(assign): reduce scalar allocations with measured Linux evidence (#…
caomengxuan666 commentedon Oct 16, 2026
First slice up as PR #672 (branch
perf/issue609-scalar): whitelist fast RHS forliteral/``/""(one borrowed read; binding path untouched). 100k `t=` 1096ms->927ms (1.18x); battery 30/30. Gate running. Remainder (dual-store write, bind clones) is later slices.perf(executor): fast RHS for plain scalar assignments (#609) (#672)
caomengxuan666 commentedon Oct 16, 2026
Slice 1 landed as #672 (squash-merged e5f7c7a). 100k t=$S 1096ms->927ms; battery 30/30; gates identical (niu 49=49). Issue stays open for slice 2 (dual-store write, bind clones).
caomengxuan666 commentedon Oct 16, 2026
Slice 2 up as PR #678 (branch
perf/issue609-slice2): marks-free bind via one attr probe, in-place dual write, identical-rebind skip (readonly still diagnoses). Net assign 2.03us->1.33us (-35%), GNU 1.25us; battery 30/30. Gate running.perf(executor): marks-free scalar bind without the dual-store walk (#609
caomengxuan666 commentedon Oct 16, 2026
Slice 2 landed as #678 (squash-merged 952ee84). Net assign 2.03us->1.33us (-35%), GNU 1.25us; battery 30/30; gates identical (niu 49=49).
caomengxuan666 commentedon Oct 16, 2026
Fixed by slices 1+2 (#672, #678). Net assign cost 2.03us->1.33us vs GNU 1.25us (1.06x, inside the 1.2x target); battery 30/30. Raw-loop remainder is loop machinery, tracked in #607.
docs: close out #607/#609/#619 lanes in ledger + changelog
docs(readme): overhaul — Performance section with pinned numbers, hon…
perf(assign): widen the marks-free scalar bind lane by attribute shap…