Skip to content

perf(transport): eliminate full-string heap reallocation in write_ndjson framing - #75

Merged
ZhuchkaTriplesix merged 1 commit into
devfrom
issue/50-write-ndjson-zero-alloc-framing
Sep 29, 2026
Merged

ZhuchkaTriplesix merged 1 commit into
devfrom
issue/50-write-ndjson-zero-alloc-framing

Conversation

@ZhuchkaTriplesix

Copy link
Copy Markdown
Member

Summary

write_ndjson (src/transport/framing.rs) sanitized raw \n/\r bytes in a payload by collecting the entire string into a new String via .chars().map(...).collect(). Every multi-megabyte tabular response containing a stray newline (an error message, embedded query text, etc.) paid for a full extra heap copy of the whole payload just to swap a handful of bytes for spaces.

\n and \r are single-byte ASCII code points, so the sanitization is now a byte-slice scan: the clean slice up to each newline is written straight to writer, followed by a single space byte, and start advances past it — no intermediate String is ever allocated. A payload with no newlines (the common case) still goes out in one write_all call, same as before.

Closes #50

Test plan

  • cargo test — 112/112 passing, including two new regression tests: newline as the very first/last byte plus consecutive newlines (empty slice between them), and a realistic multi-megabyte payload
  • cargo fmt --all -- --check
  • cargo clippy --all-targets --all-features -- -D warnings

…son framing. Closes #50

write_ndjson sanitized raw '\n'/'\r' bytes by collecting the entire
payload into a new String via .chars().map(...).collect(), so every
multi-megabyte tabular response containing a stray newline (e.g. in an
error message or embedded query text) got a full extra heap copy just
to swap a handful of bytes for spaces.

'\n' and '\r' are single-byte ASCII code points, so this rewrites the
sanitization as a byte-slice scan: write the clean slice up to each
newline straight to the writer, then a single space byte, and advance
past it — no intermediate String is ever allocated. A payload with no
newlines (the common case) still goes out in one write_all call, same
as before.
@ZhuchkaTriplesix
ZhuchkaTriplesix merged commit 2dd17bc into dev Sep 29, 2026
2 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