Skip to content

perf: optimize splitCookiesString with charCode checks#91564

Open
benfavre wants to merge 2 commits intovercel:canaryfrom
benfavre:perf/optimize-split-cookies
Open

perf: optimize splitCookiesString with charCode checks#91564
benfavre wants to merge 2 commits intovercel:canaryfrom
benfavre:perf/optimize-split-cookies

Conversation

@benfavre
Copy link
Contributor

Summary

Optimize splitCookiesString in packages/next/src/server/web/utils.ts by replacing per-character regex matching with integer charCode comparisons.

Problem

The skipWhitespace() helper creates a /\s/ regex on every call and uses charAt() which allocates a single-character string. This function is called in a tight character-scanning loop for every cookie header on every request.

Changes

  • Replace /\s/.test(cookiesString.charAt(pos)) with isWhitespace(cookiesString.charCodeAt(pos)) using a simple integer comparison helper
  • Replace charAt() comparisons in notSpecialChar() and the main loop with charCodeAt() integer comparisons
  • Zero behavioral change — same characters are matched

Why this matters

Inspired by TanStack Start's 5.5x SSR throughput: hot-path micro-optimizations compound. Regex creation and string allocation in tight loops are exactly the kind of overhead that adds up across thousands of requests.

Test plan

  • Verify cookie parsing works correctly with compound set-cookie headers
  • Verify middleware cookie forwarding still works
  • No regressions in cookie handling

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@nextjs-bot
Copy link
Collaborator

nextjs-bot commented Mar 18, 2026

Allow CI Workflow Run

  • approve CI run for commit: a60fcc9

Note: this should only be enabled once the PR is ready to go and can only be enabled by a maintainer

Adds charCode 11 (vertical tab) that the original /\s/ regex matched,
fixing a behavioral regression.
@benfavre
Copy link
Contributor Author

Test Verification

  • utils.test.ts: 4/4 passed
  • test/unit/split-cookies-string.test.ts: 10/10 passed
  • Vertical tab (charCode 11) added per VADE feedback

All tests run on the perf/combined-all branch against canary. Total: 203 tests across 13 suites, all passing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants