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 runs, best-of-3.
Composite script (the worst gap in the benchmark set):
s=abcdefghijklmnopqrstuvwxyz
t=""
for ((i=0; i<30000; i++)); do
t=${s//a/X} # global pattern replacement
t=${t^^} # uppercase all
t=${t#X} # remove prefix
t=${t%Z} # remove suffix
donebash 0.325s vs niu 1.198s → 3.69x.
Per-operation isolation (30k iterations each, same shell pair, raw totals; the empty-loop baseline extrapolates to ~0.086s bash / ~0.203s niu from the 200k : benchmark):
| op | bash | niu | ratio | op-only delta (bash / niu) |
|---|---|---|---|---|
t=${s//a/X} |
0.122s | 0.374s | 3.07x | 0.036s / 0.171s → 4.7x |
t=${s^^} |
0.113s | 0.401s | 3.55x | 0.027s / 0.198s → 7.3x |
t=${s#Q} (no match) |
0.124s | 0.320s | 2.58x | 0.038s / 0.117s |
t=${s%Q} (no match) |
0.125s | 0.324s | 2.59x | 0.039s / 0.121s |
t=$S (control) |
0.086s | 0.234s | 2.72x | assignment path — see the assignment-path issue |
Root cause (all citations verified against this checkout)
1. ${x^^} runs a heap allocation + a full glob-matcher invocation per character (the 7.3x item)
apply_parameter_case_mod (src/executor/parameter_case.rs:114-158):
let pattern = if pattern.is_empty() { "?" } else { pattern };
...
value.chars().enumerate().map(|(char_index, ch)| {
let char_value = ch.to_string(); // ← heap String per char
let matches = case_pattern_matches(pattern, &char_value); // ← matcher per char
...For a 26-char value × 30k iterations that is 780k String allocations + 780k matcher calls, where each matcher call (src/executor/conditional/pattern.rs:1-16) first runs literal_pattern_equality, then simple_glob_matches whose entry does a pattern.bytes().all(...) classification scan — for the implicit "?" pattern, every single time.
GNU does none of this when no pattern is given. Spec (third_party/bash, bash @b4608166):
subst.c:9652(parameter_brace_casemod):lpat = p ? savestring (p) : 0;→pat = lpat ? getpattern(...) : 0— the pattern is NULL for${x^^}.lib/sh/casemod.c:99(sh_modcase): "If PAT is null, modify the case of each character" — thestrmatchcall sits insideif (pat)(casemod.c:139-146) and the per-charsubstring()allocation likewise; the result buffer is allocated once (xmalloc(2*end + 1), casemod.c:124).
The fix is the whitelist-shaped fast path the code already half-has: when the (defaulted) pattern is the implicit ? / empty, transform directly with a preallocated buffer and no per-char allocation or matching — exactly sh_modcase(pat == NULL). When a real pattern is present, pass a borrowed char slice to the matcher instead of ch.to_string().
2. ${x//pat/rep} — per-call pattern re-derivation + staging (src/executor/parameter_replace.rs)
- Literal fast path (
pattern_contains_globfalse,parameter_replace.rs:74-80) →replace_with_amp→LiteralMatches::newcollects twoVecs per call:value.char_indices().collect()andneedle.chars().collect()(parameter_replace.rs:915-923), then a linear scan. The index/needle vectors depend only on (value, pattern) — the value vector at least is needed, but needle + classification can be hoisted per expansion. - Before that:
normalize_parameter_pattern_backslashes(pattern)runs three unconditionalstr::replacepasses (parameter_replace.rs:151-159), and the marker conversion atparameter_replace.rs:88-91allocates a new String even when the marker is absent. - Dispatcher fixed cost per expansion: the pattern and replacement each go through
expand_parameter_pattern_word(full word-expansion pass over a literal),nocasematch_enabled()+extglob_enabled()shopt lookups (parameter_patterns.rs:192-200), anddecode_parameter_pattern_quotesallocates aVec<char>of the pattern (parameter_decode.rs:271).
Nothing in this per-call work depends on the loop iteration — it is re-derived 30k times.
3. ${x#pat} / ${x%pat} — matcher run per candidate boundary, no matches-nowhere precheck
remove_matching_prefix/remove_matching_suffix (src/executor/parameter_decode.rs:89-140) walk every char boundary and call removal_pattern_matches(pattern, &value[..end], extglob) per boundary (parameter_decode.rs:106-110, :131-137) → case_pattern_matches again. On a non-matching literal pattern that is O(n) matcher invocations per removal; the repo itself documents this as the hot cost — conditional/pattern.rs:39-42: "the Vec staging this port paid per call is charged once per CANDIDATE BOUNDARY by the ${v#pat}/${v%pat} removal loops (parameter_decode.rs), which is the hot per-fragment cost of expansion-heavy scripts" (the Vec staging was removed in rubash#281; the per-boundary matcher calls remain).
GNU is aware of exactly this cost and pre-fails: match_upattern (third_party/bash/subst.c:5328+) — "If the pattern doesn't match anywhere in the string, go ahead and short-circuit right away. A minor optimization, saves a bunch of unnecessary calls to strmatch (up to N calls for a string of N characters) if the match is unsuccessful." rubash's // path has shape-based prunes (parameter_replace.rs:264-280: bound + literal-tail) but the #/% removal loops have no equivalent literal precheck.
Additionally every removal pays the dispatcher (expand_parameter_pattern_removal, parameter_patterns.rs:101-188): expand_parameter_pattern_word, extglob_enabled() shopt lookup, then parameter_pattern_scalar_value (parameter_patterns.rs:202-244) which probes special params → dynamic_parameter_value → resolved_variable_name (nameref check) → array-subscript parse → env_vars.get before the actual removal even starts.
4. Result values are re-copied into the assignment path
Each of the four expansions assigns to t, which pays the scalar-assignment machinery (dual store + memo insert + nameref preallocation) — cross-referenced in the assignment-path issue. Together with §1-§3 this composes the measured 3.69x.
Fix directions
- §1 (biggest, zero semantic risk):
parameter_case.rs— fast path when the pattern is the implicit?: direct per-char transform into a preallocated result buffer (GNUsh_modcasecasemod.c:99-146 semantics), noto_string(), no matcher. With an explicit pattern, pass&strslices to a borrowed matcher instead of allocating per char. - §2: hoist pattern classification (literal/glob/extglob, backslash normalization, quote decode) to once-per-expansion, computed alongside
expand_parameter_pattern_word; make the marker conversions conditional oncontains(marker); reuse a single index buffer for the literal scan. - §3: add the same matches-nowhere precheck GNU has: for literal patterns a cheap
memchr-style first-char/full-substring precheck before the boundary walk (or reuse thepattern_literal_tail_endsprune shape from the//path); classify the pattern once per removal, not once per boundary. - §4: per expansion cache — cross-link assignment-path issue.
Impact
Every ${...} in a hot loop pays §1-§3; string-munging scripts (the classic sed-less bash idioms) run 3.7x slower than GNU. ^^ alone is 7.3x on the operation itself. This is the largest interpreter-side gap in the benchmark set.
Verification plan
- Local
cargo build --release+bench_niu/micro.sh(the per-op isolation script above); target ≤1.5x per op,^^op-only ≤1.2x. - Semantics: the case-mod and removal classes are covered by
casemod.tests/new-exp8.sub-style suites — run the WSL GNU Bash 5.3.0 true-baseline slice forcasemod,parameters,pat substbefore merge (AGENTS.md rule; no pattern-behavior change is intended — only the allocation/matching schedule for the patternless case, which the GNU C source above defines).
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 工作树;该 issue 的参数展开优化需在干净 worktree 做,并按 GNU source 与全套语义回归验证。
caomengxuan666 commentedon Oct 15, 2026
已落地低风险优化:
${x^^}/${x,,}无 pattern 时直接走 Unicode case mapping,跳过隐式?和 glob matcher;新增 Unicode 回归测试,定向测试通过。带 pattern 和单字符变换路径保持不变。caomengxuan666 commentedon Oct 15, 2026
Reopen: PR#611's
^^fast-path is real (1.26×) but the other two root causes this issue documented —//re-derivation and#/%boundary matching — were not touched at allMeasured 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):${s^^}${s//a/X}${s#xx}${s%xx*}The diff confirms the cause:
src/executor/parameter_replace.rs(the//per-call pattern re-derivation, root cause #2) andsrc/executor/parameter_decode.rs:89-140(the#/%per-boundary matching vs GNU's matches-nowhere short-circuit, root cause #3) have zero lines changed in #611. Even the fixed^^path remains 3.2× off GNU (the fast-path helps but the surrounding expansion pipeline still costs ~3× per op).Allocator evidence (same workloads, LD_PRELOAD interposer, unixwin/niubash#352 appendix): the string loop still allocates 2.9× bash's malloc count / 3.7× its bytes (5.94M / 189.7 MB vs 2.07M / 51.5 MB) — consistent with the per-op allocation pattern persisting outside the
^^fast-path.Reopening to request a follow-up PR covering
parameter_replace.rsandparameter_decode.rs(and the residual^^gap), with the four micro rows above as acceptance benchmarks. These counters are deterministic (<1% run-to-run), so they can serve as a CI ratchet for the series.caomengxuan666 commentedon Oct 15, 2026
Profiling evidence: string-expansion loop allocates 2.9× the calls and 3.7× the bytes of GNU bash
LD_PRELOADallocator interposer (methodology + tool: unixwin/niubash#352 profiling appendix), workloads=abcdefghijklmnopqrstuvwxyz; t=; for ((i=0;i<30000;i++)); do t=${s//a/X}; t=${t^^}; done:2.9× allocation calls, 3.7× bytes for the same work — the direct allocator-level confirmation of this issue's per-character/per-expansion allocation analysis (
${x^^}heap-allocating and glob-matching each character,//re-deriving its pattern per call). Wall time for this loop is 3.1-7.3× depending on the op mix, so the allocation stream is a large but not complete share of the gap — the CPU-side glob-matching work described here makes up the rest.Practical note for the fix series: this loop under the interposer is a stable regression probe — allocation counters are deterministic run-to-run (<1%), so
malloc/bytestotals track the fix as directly as wall time, without noise.caomengxuan666 commentedon Oct 15, 2026
Measurement correction: quiet re-measure (reopen table had run under background load) — old→new gains hold; two vs-bash ratios overstated
Same disclosure as #607: that table's old→new columns were load-immune (back-to-back sampling), but the bash column was inflated ~1.3-1.8× by a concurrent
cargo test. Quiet best-of-3:${s^^}3.2×${s//a/X}${s#xx}${s%xx*}^^fast-path gain: 1.32× quiet (359→271 — marginally better than the posted 1.26×).//and#/%old→new changed 1.02×/1.05×/1.08× —parameter_replace.rsandparameter_decode.rshave zero diff in perf(1.4.1): reduce parameter and nameref allocation overhead #611 — and all four paths remain ~2× vs GNU.niuadds +21% over the engine on^^(328 vs 271) — wrapper overhead, cross-tracked on niubash#349.Demand unchanged: follow-up PR covering
parameter_replace.rs,parameter_decode.rs, and the residual^^gap, with the quiet rows above as acceptance benchmarks (deterministic single-run alloc counters in the appendix remain valid as CI ratchets).caomengxuan666 commentedon Oct 16, 2026
First cut up as PR #666 (branch
perf/issue608-casemod): First-operator short-circuit + patternless ~~~~ direct pass + stack-buffer de-alloc. `` 500ch x20000 ~1.42s->~0.24s (~6x); guard 33/33 vs GNU. Gate running.perf(executor): de-alloc + short-circuit case-mod expansion (#608) (#666
caomengxuan666 commentedon Oct 16, 2026
Landed as #666 (squash-merged 5342238). `` ~6x, guard 33/33, gates identical (niu 49=49).
docs: changelog + perf ledger land #607 first cut and #608 (#665/#666)
docs(readme): overhaul — Performance section with pinned numbers, hon…
Merge pull request #1530 from unixwin/fix4/slice-andr