Skip to content

ext/standard: Optimize strtr() array mode bitset and prefix scan - #483

Closed
iliaal wants to merge 1 commit into
masterfrom
opt/strtr-array-bitset-scan
Closed

iliaal wants to merge 1 commit into
masterfrom
opt/strtr-array-bitset-scan

Conversation

@iliaal

@iliaal iliaal commented Nov 27, 2026

Copy link
Copy Markdown
Owner

php_strtr_array_ex() allocated a heap length bitset scaled by input length (and 8x oversized by dividing by sizeof(zend_ulong) instead of bits) and scanned input byte-by-byte.

Use 32-byte stack bitsets for first bytes, second bytes, and key lengths under 256 (allocating on the heap sized by maxlen only when maxlen >= 256), scan with memchr() when all patterns share one first byte and 16-byte SIMD for 2 to 4 distinct first bytes, pre-filter multi-byte keys on the second byte, and move ZEND_HAS_OOM() to match handling.

On ARM64 (Neoverse-N1, GCC 13.3 -O2 NTS): 1 MB no-match 32.64x (-96.93%), 256 KB template 1.90x (-47.32%), 20-word replacement 1.87x (-46.58%), short 32 B string 1.14x (-12.25%), 4-char escape 1.05x (-5.03%).

strtr() with an array of replacements allocated a key-length bitset sized by
the input length, eight times larger than needed because it used one bit per
byte, and tested every input byte against the set of first bytes. Keep the
bitsets on the stack, allocating only when a key is 256 bytes or longer and
then sized by the longest key. Find candidates with memchr() when all keys
share one first byte and with a 16-byte SIMD compare for 2 to 4 first bytes,
and skip candidates whose second byte starts no key. Check ZEND_HAS_OOM()
before each appended replacement, which is where the loop allocates.

Neoverse-N1, GCC 13.3 -O2 NTS: 1 MB input with no match 32.7x, 20 word
replacements 1.25x (-36.6% instructions), 3 placeholders in a 250 KB
template 1.04x (-22.0% instructions), 4 single-byte escapes on a 20-byte
string unchanged (-1.9% instructions).
@iliaal
iliaal force-pushed the opt/strtr-array-bitset-scan branch from b243816 to 3599aa4 Compare November 27, 2026 16:46
@iliaal

iliaal commented Nov 27, 2026

Copy link
Copy Markdown
Owner Author

Submitted upstream as php/php-src phpGH-25847: php#25847

@iliaal iliaal closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant