From 8e2c4ec186947d1aff4dfb8f8a64d8025f4facf9 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 17 Oct 2024 15:07:55 -1000 Subject: [PATCH] Improve performance of creating the ConnectionKey Reuses the same idea as https://github.com/aio-libs/yarl/pull/1316 and https://github.com/aio-libs/yarl/pull/1322 Calling `tuple.__new__` is much faster because it avoids the extra runtime lambda having to be run and arguments unpacked for every message https://github.com/python/cpython/blob/d83fcf8371f2f33c7797bc8f5423a8bca8c46e5c/Lib/collections/__init__.py#L441 This only works if the object being created is a `NamedTuple` so this speed up is only recommended internally and should not be used outside of `aiohttp` since we do not guarantee that ConnectionKey will remain a `NamedTuple` in the future. --- aiohttp/client_reqrep.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index 9cc491669b..602d6da5f9 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -304,14 +304,17 @@ def connection_key(self) -> ConnectionKey: else: h = None url = self.url - return ConnectionKey( - url.raw_host or "", - url.port, - url.scheme in _SSL_SCHEMES, - self._ssl, - self.proxy, - self.proxy_auth, - h, + return tuple.__new__( + ConnectionKey, + ( + url.raw_host or "", + url.port, + url.scheme in _SSL_SCHEMES, + self._ssl, + self.proxy, + self.proxy_auth, + h, + ), ) @property