Skip to content

Commit e6c071a

Browse files
committed
Skip filtering CookieJar when the jar is empty or all cookies have expired (aio-libs#7819)
The filtering itself and its preparation in `CookieJar.filter_cookies()` is expensive. Sometimes there are no cookies in the jar or all cookies have expired. Skip filtering and its preparation in this case. Because the empty check is much cheaper than `_do_expiration()`, I think it deserves to be duplicated before and after calling `_do_expiration()`. ```console $ python3.11 -m timeit -s 'from collections import defaultdict; d=defaultdict(foo="bar")' \ > 'if not d: pass' 50000000 loops, best of 5: 8.3 nsec per loop $ python3.11 -m timeit -s 'from collections import defaultdict; d=defaultdict()' \ > 'if not d: pass' 50000000 loops, best of 5: 8.74 nsec per loop $ python3.11 -m timeit -s 'from aiohttp import CookieJar; cj = CookieJar()' \ > 'cj._do_expiration()' 200000 loops, best of 5: 1.86 usec per loop ``` (cherry picked from commit dfc3f89)
1 parent fffc433 commit e6c071a

File tree

3 files changed

+10
-2
lines changed

3 files changed

+10
-2
lines changed

CHANGES/7819.feature

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Skip filtering ``CookieJar`` when the jar is empty or all cookies have expired.

CONTRIBUTORS.txt

+1
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ Required Field
273273
Robert Lu
274274
Robert Nikolich
275275
Roman Podoliaka
276+
Rong Zhang
276277
Samir Akarioh
277278
Samuel Colvin
278279
Sean Hunt

aiohttp/cookiejar.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -236,11 +236,17 @@ def filter_cookies(
236236
self, request_url: URL = URL()
237237
) -> Union["BaseCookie[str]", "SimpleCookie[str]"]:
238238
"""Returns this jar's cookies filtered by their attributes."""
239-
self._do_expiration()
240-
request_url = URL(request_url)
241239
filtered: Union["SimpleCookie[str]", "BaseCookie[str]"] = (
242240
SimpleCookie() if self._quote_cookie else BaseCookie()
243241
)
242+
if not self._cookies:
243+
# Skip do_expiration() if there are no cookies.
244+
return filtered
245+
self._do_expiration()
246+
if not self._cookies:
247+
# Skip rest of function if no non-expired cookies.
248+
return filtered
249+
request_url = URL(request_url)
244250
hostname = request_url.raw_host or ""
245251
request_origin = URL()
246252
with contextlib.suppress(ValueError):

0 commit comments

Comments
 (0)