Skip to content

Count a UTF-8 form body's length without encoding - #2423

Open
pavel-ptashyts wants to merge 1 commit into
AsyncHttpClient:mainfrom
maygemdev:pavel-ptashyts/perf-content-length-once
Open

pavel-ptashyts wants to merge 1 commit into
AsyncHttpClient:mainfrom
maygemdev:pavel-ptashyts/perf-content-length-once

Conversation

@pavel-ptashyts

@pavel-ptashyts pavel-ptashyts commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When the caller sets a Content-Length header, NettyRequestSender.sendRequest calls NettyRequestFactory.checkContentLength(Request) before it takes a pooled connection (added in #2407, so that a request that cannot be built does not take a connection out of the pool). For a form body that check learned the length by building the body: urlEncodeFormParams(...).remaining() url-encodes every param into a pooled StringBuilder and copies it into a byte[]. newNettyRequest then encodes the same params again in body(). So every attempt (first send, retry, redirect, auth replay) encoded the form twice and allocated the encoded body once more as garbage.

Change

For UTF-8 (the default request charset), checkContentLength now counts the encoded length from the params, following Utf8UrlEncoder.encodeAndAppendFormElement: a char in its form-safe set (a-z A-Z 0-9 - . _ *) is 1, a space is 1 (+), any other ASCII char is 3 (%XX), and any other code point is 3 per byte of its UTF-8 form, with an unpaired surrogate taking 3 bytes as the encoder writes it; params are joined by &, and a null value has no =. The encoder's output is ASCII, so chars are bytes. Other charsets keep the old path (URLEncoder.encode per field).

The body is still built once per attempt in body(), from the request, as before. Nothing is cached on the Request or across attempts.

String bodies are deliberately left alone

I also tried counting the UTF-8/ISO-8859-1/US-ASCII length of a setBody(String) body char by char. It is exact and allocation-free, but String.getBytes on an ASCII String is an intrinsic array copy, and no char loop I tried (plain loop, OR-reduction pre-scan, chunked getChars) came close, on JDK 11 or 25:

JDK 11, 65,536 chars getBytes(UTF_8).length char-by-char count
ascii 6.1 us 36.5 us
latin1 56.5 us 38.8 us
cyrillic 83.0 us 26.6 us

Trading a short-lived allocation for 3 to 6 times the CPU on the most common body (ASCII JSON) is not a gain, so the String path is unchanged.

Preserved behaviour

  • A malformed, duplicated or mismatching Content-Length still fails in checkContentLength, before a pooled connection is taken, with the same IllegalArgumentException and message.
  • CONNECT handling, body precedence (still body()'s order), charset semantics and header validation are untouched; the only change is how the form length is obtained in the preflight.
  • No public API change: the new helpers are package-private/private in NettyRequestFactory. Revapi passes.
  • HTTP/2 shares this preflight and gets the same result.

Benchmark

New ContentLengthPreflightBenchmark runs the real checkContentLength(Request) for a request with a matching header. length is the text length in chars before encoding (the 200-char Cyrillic form encodes to about 1,200 bytes). The same benchmark was run against main's NettyRequestFactory (before) and this branch (after). JDK 11.0.33, -f 1 -wi 3 -i 5 -prof gc, -Xmx256m; the host was shared with other builds, so take times as indicative. B/op is deterministic.

body length text ns/op before -> after B/op before -> after
form 200 ascii 1,002 -> 497 408 -> 24
form 200 multibyte 1,973 -> 340 1,136 -> 48
form 65,536 ascii 313,698 -> 93,277 117,105 -> 48
form 65,536 multibyte 635,584 -> 103,798 346,482 -> 48
string 200 ascii 27 -> 27 264 -> 264
string 200 multibyte 229 -> 231 1,032 -> 1,032
string 65,536 ascii 6,114 -> 6,116 65,576 -> 65,600
string 65,536 multibyte 83,689 -> 83,649 318,400 -> 318,400

The String rows are the control and do not change. The gain only applies to requests with a form body and an explicit Content-Length, which is not a common combination; for those, the preflight goes from a full second encoding to a scan.

Tests

NettyRequestFactoryContentLengthTest (new):

  • the counted form length equals urlEncodeFormParams(params, charset).remaining() for every char U+0000..U+FFFF as name and value (UTF-8), and, for UTF-8, ISO-8859-1, US-ASCII, UTF-16 and windows-1252, for ASCII, Latin-1, Cyrillic, CJK, surrogate pairs, unpaired surrogates in every position, null values and 1,000 seeded random param pairs;
  • a matching header is accepted, and a mismatching (0, length - 1, length + 1) or malformed (+n, n, n, abc) header is rejected with the same message, for String and form bodies, ASCII and multi-byte text, UTF-8 and ISO-8859-1.

The existing CallerContentLengthTest, NettyRequestFactoryStringBodyTest and HttpUtilsTest pass unchanged. The new test also passes on JDK 25.

Gate: mvnw.cmd -B -ntp -Dgpg.skip=true clean verify on JDK 11.0.33 (Corretto): BUILD SUCCESS, 2,510 tests, 0 failures, 0 errors, 47 skipped; Revapi passed.

AI disclosure

Claude Code on behalf of Pavel Ptashyts. The commit carries a Co-Authored-By trailer per AGENTS.md.

🤖 Generated with Claude Code

When the caller sets Content-Length, NettyRequestSender checks it
before taking a pooled connection, and for a form body it learned the
length by url-encoding the params into a pooled StringBuilder and
copying that into a byte array. newNettyRequest then encodes the same
params again for the body, so every attempt encoded the form twice.

For UTF-8, the default, the length of the encoded form follows from
the params alone: Utf8UrlEncoder keeps a fixed set of ASCII chars,
writes a space as '+' and any other code point as %XX per UTF-8 byte,
and its output is ASCII. The check now counts that instead. Other
charsets keep the old path. A matching, mismatching or malformed
header fails exactly as before, with the same message.

String bodies are left alone: String.getBytes is an array copy for
ASCII text, and counting UTF-8 bytes char by char was 3 to 6 times
slower there, on JDK 11 and 25.

Claude Code on behalf of Pavel Ptashyts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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