perf: amortize in-place string concatenation by moreal · Pull Request #8629 · RustPython/RustPython · GitHub
Skip to content

perf: amortize in-place string concatenation - #8629

Draft
moreal wants to merge 2 commits into
RustPython:mainfrom
moreal:perf/str-inplace-concat
Draft

perf: amortize in-place string concatenation#8629
moreal wants to merge 2 commits into
RustPython:mainfrom
moreal:perf/str-inplace-concat

Conversation

@moreal

@moreal moreal commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Summary

Repeated in-place string concatenation previously allocated an exactly sized buffer and copied the entire left-hand string for every append. A loop using s += piece therefore scaled quadratically.

Store owned string data in a capacity-bearing Wtf8Buf and reuse that allocation when the left operand is uniquely owned. String kind and character length are packed into one atomic metadata word so the payload remains five machine words. Shared left operands retain copy-on-write behavior, and cached hash/index state is invalidated when a unique string is extended.

This is an internal performance change. Python-visible string immutability and concatenation behavior are unchanged.

Performance

benches/microbenchmarks/str_inplace_concat.py repeatedly appends a short string to an initially empty string. Comparing the benchmark-only baseline with this change:

Appends Baseline This PR Change
2,000 300.09 µs 118.53 µs -60.5%
6,000 1.5901 ms 358.20 µs -77.1%
10,000 3.7417 ms 599.05 µs -83.9%
14,000 6.7585 ms 840.36 µs -87.5%
18,000 10.701 ms 1.0819 ms -89.7%

From 2,000 to 18,000 appends, the final implementation takes about 9.1× as long for 9× the work, showing approximately linear scaling. The baseline takes about 35.7× as long over the same range.

Appendix: builtin_hash snippet failure

The Ubuntu snippet job fails in extra_tests/snippets/builtin_hash.py at the first assertion that hashing a tuple nested 100,000 levels must raise RecursionError. On that build, hash(deep_tuple) completes normally, so the following dictionary and set assertions are not reached.

This PR does not change tuple hashing or the native-stack guard. The test uses a fixed nesting depth as a proxy for reaching that guard, but the guard checks the actual stack pointer and therefore only raises when the native stack approaches its soft limit. Optimized native frame size is platform- and code-generation-dependent.

A local arm64 macOS comparison used identical --release --features=threading,jit builds of the benchmark-only parent (the same interpreter code as the branch base) and this PR:

Measurement Baseline This PR
Native stack per tuple-hash level 224.08 B 192.07 B
Deepest measured successful hash 36,990 43,150
First measured RecursionError 37,000 43,175
PyObject::hash native frame 144 B (0x90) 112 B (0x70)

The runtime measurement and disassembly agree on an exact 32-byte reduction per recursive level. Both local builds still reach the same physical stack margin, raise RecursionError well before 100,000 levels, and pass the snippet. The Ubuntu result is consistent with its optimized frame becoming small enough that 100,000 levels no longer reach the guard. In other words, the failure is caused by the fixed-depth test depending on generated native frame size, not by a change to string semantics or by disabling the stack guard. A local CPython 3.14.7 build also hashes the same 100,000-level value successfully, so raising at that exact depth is not a Python-visible compatibility requirement.

AI assistance

Codex (gpt-5.6-sol) assisted extensively with the design, implementation, tests, correctness validation, benchmark construction and measurement, code review, and drafting this PR description.

@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the z-ca-2026 Tag to track Contribution Academy 2026 label Aug 31, 2026
@codspeed-hq

codspeed-hq Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will degrade performance by 21.51%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
❌ 1 regressed benchmark
✅ 64 untouched benchmarks
🆕 1 new benchmark

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
gc_collect.py[rustpython] 79.2 ms 143.8 ms -44.92%
gc_traversal.py[rustpython] 771.7 ms 689.8 ms +11.87%
🆕 rustpython[str_inplace_concat.py] N/A 26.4 ms N/A

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing moreal:perf/str-inplace-concat (1c58b2a) with main (287dcd9)

Open in CodSpeed

Assisted-by: Codex:gpt-5.6-sol
Assisted-by: Codex:gpt-5.6-sol
@moreal
moreal force-pushed the perf/str-inplace-concat branch from 9e11753 to 1c58b2a Compare September 2, 2026 17:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

z-ca-2026 Tag to track Contribution Academy 2026

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant