ReviewOS

stacks/bun-router

perf: the response helpers serialize a body and then leave its length off

#895
Closed chris opened this 8 days ago ·
8 days ago

Same shape as #892, in the other module that builds bodies.

response.json(), response.view(), response.text(), response.xml() and response.tooManyRequests() each serialize a body and hold the finished string. None of them states Content-Length.

That is what lets the compression layer reject a sub-threshold body without opening its stream. Without it, every response these helpers build goes through peekBody - and a reader loop over an in-memory body costs several times what returning the response costs (measured at a fixed 8,000 req/s on a 17-byte JSON body: 20.8 us to return it, 36.7 us to read it back through a reader).

It matters most where these helpers actually get used, which is the unhappy paths: validation failures, rate-limit refusals, error envelopes. Those already cost more than a success; they should not also pay for a stream.

The helpers now state the byte length of what they serialized. A caller's own Content-Length still wins, and noContent() - which builds no body - is untouched.

Sign in to comment on this issue.