[php-src] PR #17734: Optimize JSON string encoding
| From: | nielsdos | Date: | Sat, 08 Feb 2025 00:09:20 +0000 |
| Subject: | [php-src] PR #17734: Optimize JSON string encoding | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-30698@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/17734
Author: nielsdos
* Split out a specialized function to decode multibyte UTF-8 sequences
Decoding purely multibyte UTF-8 is common for example in the case of
JSON. Furthermore, we want to avoid the switch on the character set in
such hot code. Finally, we also add UNEXPECTED markers to move code to
the cold section which reduces pressure on the µop and instruction
caches.
* Optimize JSON string encoding
There are a couple of optimizations that work together:
- We now use the specialized php_next_utf8_char_mb() helper function to
avoid pressure on the µop and instruction cache.
- It no longer emits UTF-8 bytes under PHP_JSON_UNESCAPED_UNICODE until
it actually has to. By emitting in bulk, this improves performance.
- Code layout tweaks
* Use a specialized php_json_append() and assertions to avoid
allocating the initial buffer, as this is already done upfront.
* Factor out the call to smart_str_extend() to above the UTF-16 check
to avoid code bloat.
- Use SIMD, either with SSE2 or SSE4.2. A resolver is used when SSE4.2
is not configured at compile time.
Here's a graph where I test different input strings.
The tests take an input string and repeat it using
str_repeat, and then perform
200000 calls to json_encode with no flags. If (no escape) is
in the label, then we pass JSON_UNESCAPED_UNICODE as a flag.
The first four bars show the very short strings where performance improvements won't be able to
do much and no SIMD is possible. The performance difference and overhead of this approach is IMO
negligible in those cases.
Next we test some extreme cases. The best case happens when a string doesn't need escaping or
anything special. We can see when we need to do escaping or UTF-8 validation/escaping that the
performance win is still there, but not as pronounced.
In some extreme UTF-8 (éa*200) the performance is slightly lower but when compared to
the total execution time this shouldn't be noticeable. The last two bars show that the
performance when using JSON_UNESCAPED_UNICODE is improved as well, which is hopefully
the common way people work with UTF-8 in JSON.

The benchmark gist is here: https://gist.github.com/nielsdos/51f32ca9d4610b802d0ea65e7af6ae16