From 5b5eb8bc38976dc360138e79a2ca405d5650fea4 Mon Sep 17 00:00:00 2001 From: Cycloctane Date: Fri, 25 Jul 2025 06:37:42 +0800 Subject: [PATCH] small speedup by avoiding redundant `IOBasePayload.size` calls (#11335) --- aiohttp/multipart.py | 5 +++-- aiohttp/web_response.py | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py index befb1e8c373..a3a40080b12 100644 --- a/aiohttp/multipart.py +++ b/aiohttp/multipart.py @@ -980,14 +980,15 @@ def size(self) -> Optional[int]: """Size of the payload.""" total = 0 for part, encoding, te_encoding in self._parts: - if encoding or te_encoding or part.size is None: + part_size = part.size + if encoding or te_encoding or part_size is None: return None total += int( 2 + len(self._boundary) + 2 - + part.size # b'--'+self._boundary+b'\r\n' + + part_size # b'--'+self._boundary+b'\r\n' + len(part._binary_headers) + 2 # b'\r\n' ) diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index dc4c16804d7..41559143b6a 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -690,8 +690,8 @@ async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: del self._headers[hdrs.CONTENT_LENGTH] elif not self._chunked: if isinstance(self._body, Payload): - if self._body.size is not None: - self._headers[hdrs.CONTENT_LENGTH] = str(self._body.size) + if (size := self._body.size) is not None: + self._headers[hdrs.CONTENT_LENGTH] = str(size) else: body_len = len(self._body) if self._body else "0" # https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-7