#65483 closed defect (bug) (fixed)
Improve UTF-8 scanning performance with codepoint limits
| Reported by: | jonsurrell | Owned by: | jonsurrell |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.1 |
| Component: | Charset | Version: | 6.9 |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: | performance |
Description
_wp_scan_utf8() includes a fast-path for scanning past ASCII bytes. The function also exposes optional byte and codepoint limits.
The ASCII fast-path relies on strspn() with a length limit in case a byte range has been provided. It does not limit the scan length if a codepoint limit has been provided but no byte limit. In this case strspn() will scan through to the end of the string even if a single codepoint remains to be matched which could be satisfied by checking a single byte for ASCII.
The missing codepoint limit on the ASCII fast-path is likely the cause of the issue mentioned in this comment.
Change History (3)
This ticket was mentioned in PR #12214 on WordPress/wordpress-develop by @jonsurrell.
3 months ago
#1
- Keywords has-patch has-unit-tests added
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
When
_wp_scan_utf8()is invoked with a maximum number of codepoints, the ASCII fast-path will still scan the entire input string. In the case of long ASCII-only strings searching for a limited number of codepoints, this is wasteful and can be optimized by only searching up to remaining number of desired codepoints.ASCII are all 1-byte UTF-8 codepoints, so the maximum number of ASCII bytes can be limited by the maximum number of remaining codepoints.
See the demonstration below.
https://github.com/WordPress/wordpress-develop/blob/c710ca6b53db970d1b59b4e34ba130b25458ec1b/src/wp-includes/compat-utf8.php#L56-L69
<details>
<summary>Demonstration</summary>
Output diff:
trunk@ c710ca6b53db970d1b59b4e34ba130b25458ec1b.txt
53752292ms.4417ms.1005872250ms.978311000ms:</details>
This seems to address a performance issue inspecting a 10MB XML file. The file is mostly ASCII (>98%), and at each codepoint boundary the rest of the document was scanned to find the ASCII code point count, often reading very large chunks of the document repeatedly. This is fixed by recognizing the max codepoint limit in the ASCII fast path.
<details><summary>performance benchmark results</summary>
### Before (trunk@ c710ca6b53db970d1b59b4e34ba130b25458ec1b )
Timed:
8.93s user 0.02s system 99% cpu 8.982 total### After (branch@ 5829e041927202bcf421c318f5177a01c303a4b5 )
Timed:
0.19s user 0.01s system 96% cpu 0.214 total</details>
Follow-up to: r60768
Trac ticket: https://core.trac.wordpress.org/ticket/65483
## Use of AI Tools
AI assistance: Yes
Tool(s): Claude (Fable 5, Opus 4.8, etc.), Codex (GPT 5.5)
Used for: Fuzz testing and discovery, implementation, testing..