Skip to content

Optimize JSON serializer#5

Merged
colemancda merged 2 commits into
masterfrom
feature/serializer-performance
Jul 19, 2026
Merged

Optimize JSON serializer#5
colemancda merged 2 commits into
masterfrom
feature/serializer-performance

Conversation

@colemancda

@colemancda colemancda commented Jul 19, 2026

Copy link
Copy Markdown
Member

Summary

Rewrites the serializer core to write into a [UInt8] buffer instead of building a String and re-walking it. Public API (toString / toData / SerializationOptions) and output are unchanged and byte-identical. All techniques are Embedded-safe.

Independent of the parser work in #4 (different file), so the two can merge in any order.

Changes

  • Byte-buffer coretoData() returns the accumulated [UInt8] directly; toString() wraps it in String(decoding:). Previously toData() built a String then re-encoded it to UTF-8 — two full traversals.
  • Bulk string escaping — escape-free runs (the common case, including object keys) are appended in one append(contentsOf:) over the source UTF-8, replacing the per-unicodeScalar append.
  • Integer formatting without allocation — signed/unsigned integers are written digit-by-digit into a stack buffer (withUnsafeTemporaryAllocation), replacing .description String allocations. Int64.min handled via unsigned negation.
  • Static hex table — the \u00XX control-escape table is a static [UInt8] instead of a [Character] array rebuilt on every string.

Performance (1.10 MB output / 5000 objects, release, Apple Silicon)

Serializer Throughput
master toData() ~47 MB/s
this branch toData() ~164 MB/s
this branch toString() ~157 MB/s
reference ~200 MB/s

~3.5× faster; the remaining 1.22× vs the reference is its buffer capacity pre-estimate (a recursive size walk we chose not to add — diminishing returns for the extra pass).

Verification

  • 51 tests pass (added integer 0 / min / max, empty and escaped string serialization cases)
  • Coverage 99.89%, serializer file 100%
  • wasm-embedded release build clean

@github-code-quality

Copy link
Copy Markdown

Code Coverage Overview

Languages: Swift

Swift / code-coverage/llvm-cov

The overall coverage in the feature/serializer-p... branch is 100%. The coverage in the master branch is 99%.

Show a code coverage summary of the most impacted files.
File master e8f9204 feature/serializer-p... a146328 +/-
Sources/JSONMac...ONCodable.swift 100% 0% -100%
Sources/JSONMacros/Error.swift 100% 0% -100%
Sources/JSON/Serializer.swift 100% 100% 0%
Sources/JSONMac...os/Macros.swift 0% 0% 0%
Sources/JSON/Parser.swift 99% 100% +1%

Code Coverage is in Public Preview. Learn more and provide us with your feedback.

@colemancda
colemancda merged commit 159ec30 into master Jul 19, 2026
11 checks passed
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