Skip to content

[perf][P1] Parameter expansion 2.6-7.3x slower than GNU: ${x^^} heap-allocates and glob-matches every character (GNU transforms directly when pat==NULL), plus per-call pattern re-derivation in // and #/% #608

Closed

Description

@caomengxuan666

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
done

bash 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" — the strmatch call sits inside if (pat) (casemod.c:139-146) and the per-char substring() 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_glob false, parameter_replace.rs:74-80) → replace_with_amp → LiteralMatches::new collects two Vecs per call: value.char_indices().collect() and needle.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 unconditional str::replace passes (parameter_replace.rs:151-159), and the marker conversion at parameter_replace.rs:88-91 allocates 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), and decode_parameter_pattern_quotes allocates a Vec<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. §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 (GNU sh_modcase casemod.c:99-146 semantics), no to_string(), no matcher. With an explicit pattern, pass &str slices to a borrowed matcher instead of allocating per char.
  2. §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 on contains(marker); reuse a single index buffer for the literal scan.
  3. §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 the pattern_literal_tail_ends prune shape from the // path); classify the pattern once per removal, not once per boundary.
  4. §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 for casemod, parameters, pat subst before 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; 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。当前 checkout 含他人未跟踪文件,按协作规则暂不直接编辑 rubash 工作树;该 issue 的参数展开优化需在干净 worktree 做,并按 GNU source 与全套语义回归验证。

  3. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    已落地低风险优化:${x^^}/${x,,} 无 pattern 时直接走 Unicode case mapping,跳过隐式 ? 和 glob matcher;新增 Unicode 回归测试,定向测试通过。带 pattern 和单字符变换路径保持不变。

  4. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    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 all

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

    workload ×30k e785 (1.4.0) 334afab (new) GNU bash old→new new vs bash
    ${s^^} 583 ms 462 ms 144 ms 1.26× 3.2× slower
    ${s//a/X} 394 ms 392 ms 175 ms 1.01× (unchanged) 2.2× slower
    ${s#xx} 334 ms 319 ms 157 ms 1.05× 2.0× slower
    ${s%xx*} 356 ms 331 ms 159 ms 1.08× 2.1× slower

    The diff confirms the cause: src/executor/parameter_replace.rs (the // per-call pattern re-derivation, root cause #2) and src/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.rs and parameter_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.

  5. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    Profiling evidence: string-expansion loop allocates 2.9× the calls and 3.7× the bytes of GNU bash

    LD_PRELOAD allocator interposer (methodology + tool: unixwin/niubash#352 profiling appendix), workload s=abcdefghijklmnopqrstuvwxyz; t=; for ((i=0;i<30000;i++)); do t=${s//a/X}; t=${t^^}; done:

    shell malloc realloc bytes requested
    bash 5.3 2 070 738 1 51.5 MB
    niu 1.4.0 5 942 489 1 290 205 189.7 MB

    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/bytes totals track the fix as directly as wall time, without noise.

  6. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    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:

    workload ×30k rubash e785 rubash 334afab niu product GNU bash new vs bash (corrected) posted (retracted)
    ${s^^} 359 ms 271 ms 328 ms 136 ms 1.99× 3.2×
    ${s//a/X} 331 ms 325 ms 393 ms 153 ms 2.12× 2.2× ✓
    ${s#xx} 284 ms 271 ms 349 ms 133 ms 2.04× 2.0× ✓
    ${s%xx*} 287 ms 266 ms 333 ms 132 ms 2.02× 2.1× ✓

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

  7. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    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.

  8. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Landed as #666 (squash-merged 5342238). `` ~6x, guard 33/33, gates identical (niu 49=49).

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