Reuse the client cookie jar instead of copying it per request

Merged
KL
19d ago
+8-9

Stop copying the client cookie jar on every request, as reported in #1282. _merge_cookies copied it, then Request.__init__ copied it again, so each request cost time in proportion to every stored cookie. Now the client jar is used directly unless per-request cookies= need merging, and redirects reuse it too.

build_request() with cookies spread over 500 domains:

CookiesBeforeAfter
100410 µs260 µs
1,0002.4 ms1.3 ms
5,0006.3 ms2.2 ms

The remaining cost is the stdlib CookieJar.add_cookie_header(), which still scans every domain and expiry on each request. The CodSpeed benchmark from #1283 tracks this case.

AI Disclaimer

This PR was developed with the assistance of either Claude or Codex. I've reviewed and verified the changes.