Repository navigation
perf: replace format!() allocations in on_headers hot path - #1200
Conversation
Replace heap-allocating format!() calls with write!() into reusable Vec<u8> buffers and itoa for stack-based integer formatting. This eliminates up to 7 String allocations per HTTP request in the header editing callback that profiling showed taking up to 75% of readable(). Changes: - Add itoa dependency for stack-based u16 port formatting - Add write_forwarded_for_by() and write_forwarded_suffix() helpers that build Forwarded header values into a Vec<u8> without format!() - Replace format!() in X-Forwarded-For, Forwarded, Set-Cookie with write!() into reusable hdr_buf + Store::from_vec(take(&mut buf)) - Replace public_port.to_string() with itoa::Buffer for X-Forwarded-Port - Replace val.to_string() with ToOwned::to_owned for sticky cookie - Keep self.id.to_string() for Sozu-Id (Ulid encoding is already optimized with pre-allocated crockford base32 buffer)
- Remove `unsafe { from_utf8_unchecked(...) }.as_bytes()` round-trip
when extending hdr_buf with existing header data — the data is
already `&[u8]`, so the unsafe conversion to `&str` and back was
pointless and introduced gratuitous unsafety.
- Move `hdr_buf` allocation inside `if let Some(peer_addr)` block to
avoid a 128-byte heap allocation when `session_address` is `None`.
- Fix misleading "Reusable buffer" comment — the buffer's ownership
is transferred via `take`, so it is not actually reused.
- Remove unused `from_utf8_unchecked` import.
Signed-off-by: Florentin Dubois <[email protected]>
Align itoa dependency version with workspace convention: "^x.y.z" instead of "^x.y". Signed-off-by: Florentin Dubois <[email protected]>
llenotre
left a comment
There was a problem hiding this comment.
Vec::with_capacity is allocating memory, just like creating a String. The difference being that format! pre-computes the amount of memory required in the string to avoid re-allocations on grow.
As such, I think the changes in this PR give the same behaviour, but with more complicated code while potentially being less optimized?
FlorentinDUBOIS
left a comment
There was a problem hiding this comment.
Thanks for the review! The concern is fair, but format!() doesn't actually pre-compute the exact capacity needed.
Looking at the Rust source, estimated_capacity() only sums literal string parts — placeholders like {peer_ip} contribute zero. It also has a special case: when the format string starts with a placeholder and literals total < 16 bytes, it returns 0 (source — String::with_capacity(estimated_capacity())).
In practice for this PR's hot path:
| Call | Estimated capacity | Actual output |
|---|---|---|
format!("{}, {peer_ip}", value) |
0 (starts with {}, 2 bytes of literals < 16) |
~30-60 bytes |
peer_ip.to_string() / port.to_string() |
0 | 1-39 bytes |
format!("{value}, proto=…;by={public_ip}") |
~40 (literals × 2) | ~80-100 bytes with IPv6 |
So several format!() calls start from zero allocation and grow through multiple reallocations.
The main win here isn't just Vec vs String — it's the buffer reuse via std::mem::take(): a single Vec::with_capacity(128) is allocated once and reused for multiple header writes, reducing ~7 allocations per request to ~3-4. itoa::Buffer adds further savings by formatting ports entirely on the stack (no heap allocation at all).
The extracted helpers (write_forwarded_for_by, write_forwarded_suffix) also reduce the IPv4/IPv6 duplication that existed in the original code. I'll add a criterion benchmark to back this up with numbers.
Add benchmarks comparing the format!() approach vs Vec<u8> + write!() + itoa for building HTTP header values in on_headers. Measures X-Forwarded-For, Forwarded, X-Forwarded-Port, Set-Cookie, and full pipeline scenarios with both IPv4 and IPv6 fixtures. Refs: #1140 Signed-off-by: Florentin Dubois <[email protected]>
Benchmark resultsAdded a criterion benchmark (
The biggest wins are on Full pipeline: ~33% faster per request. |
…timization perf: replace format!() allocations in on_headers hot path
Summary
format!()allocations withitoa::Buffer,write!()intoVec<u8>, andextend_from_sliceitoaworkspace dependency (zero-dep, stack-based integer formatting)write_forwarded_for_byandwrite_forwarded_suffixhelpers to reduce code duplicationReview fixes applied
unsafe { from_utf8_unchecked(...) }.as_bytes()roundtrip — now uses&[u8]directlyVec::with_capacity(128)allocation into conditional scope (was allocating on every request even withoutsession_address)Closes #1140
Test plan
cargo test --workspacepassescargo clippy --workspaceclean