mirror of
https://github.com/dop251/goja.git
synced 2026-11-17 19:47:16 +00:00
* perf: implement lazy string concatenation to fix O(n²) memory blowup in += loops
The engine suffered from severe memory and performance degradation when
performing repeated string concatenation (e.g. str += "x" inside a loop).
Every += compiled down to String.Concat() which immediately allocated a
brand-new flat buffer and copied both operands in full, resulting in O(n²)
total bytes copied.
Introduce concatString, a lightweight rope-like node that defers flattening
until the content is actually needed (similar to V8's ConsString).
- Small strings (length <= 32) are still flattened immediately to avoid
tiny-object overhead.
- Large strings create a concatString{left, right, length} node with zero
data copying.
- When content is finally required, the tree is walked once, flattened into
a single asciiString / unicodeString, and cached with sync.Once.
Key changes:
- string_concat.go: new concatString type with full String interface
- string_ascii.go / string_unicode.go: Concat() returns concatString for
large results
- string.go: devirtualizeString() handles *concatString
- builtin_string.go: normalize handles *concatString
- vm.go: concatStrings instruction flattens *concatString on the stack
- string_concat_test.go: correctness tests and benchmarks
Benchmark results (100 000 iterations):
- Before: 382 ms, 5.32 GB allocated
- After: 17.8 ms, 18.4 MB allocated
- Improvement: ~23x faster, 289x less memory
* concatStrings: fixed string equality and data race on reads of the flat field. All tests now pass.
* Reduced memory footprint and allow the former parts to be garbage-collected after the string is flattened. Fixed equality.
---------
Co-authored-by: 张彦伟 <zyw4@meitu.com>
141 lines
2.2 KiB
141 lines
2.2 KiB