Repository navigation
[Perf][JSON] Improve string escaping in JSONWriter - #3469
Merged
Merged
Conversation
Count the bytes that need escaping 16 bytes at a time with SIMD. If there are none, append the whole string at once. Otherwise, grow the output once to the upper bound, copy escape-free 16 byte chunks directly, and write escapes in place, instead of appending small runs for each escape. Encoding a string that embeds JSON is about 2.9x faster, source text about 2.4x, and strings without escapes about 9x.
rintaro
requested review from
hamishknight,
hborla and
nkcsgexi
as code owners
October 8, 2026 21:06
hamishknight
approved these changes
Oct 8, 2026
Member
Author
|
@swift-ci Please test |
1 similar comment
Member
Author
|
@swift-ci Please test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
JSONWriter.serialize(string:)checked one byte at a time and made one or two smallappend(contentsOf:)calls for every escaped byte. That's slow for strings with many escapes, like a JSON document embedded as a string value, and the byte-by-byte scan also slowed down strings with nothing to escape.This PR encodes each string in two passes:
SIMD16<UInt8>, count the bytes that need escaping (",\, and control characters) and how many of them are control characters. The compiler didn't vectorize the plain loop on its own.Measured with a standalone
-O -wmobenchmark built from the encoder sources (arm64, macOS):\nevery ~70 bytes)