Skip to content

Commit 3a9de0c

Browse files
authored
[PR #8660/14d5295 backport][3.10] Improve performance of WebSockets when there is no timeout (#8663)
1 parent 1bc8d53 commit 3a9de0c

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

CHANGES/8660.misc.rst

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improved performance of :py:meth:`~aiohttp.ClientWebSocketResponse.receive` and :py:meth:`~aiohttp.web.WebSocketResponse.receive` when there is no timeout. -- by :user:`bdraco`.
2+
3+
The timeout context manager is now avoided when there is no timeout as it accounted for up to 50% of the time spent in the :py:meth:`~aiohttp.ClientWebSocketResponse.receive` and :py:meth:`~aiohttp.web.WebSocketResponse.receive` methods.

aiohttp/client_ws.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,8 @@ async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bo
281281
return False
282282

283283
async def receive(self, timeout: Optional[float] = None) -> WSMessage:
284+
receive_timeout = timeout or self._receive_timeout
285+
284286
while True:
285287
if self._waiting:
286288
raise RuntimeError("Concurrent call to receive() is not allowed")
@@ -294,7 +296,14 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
294296
try:
295297
self._waiting = True
296298
try:
297-
async with async_timeout.timeout(timeout or self._receive_timeout):
299+
if receive_timeout:
300+
# Entering the context manager and creating
301+
# Timeout() object can take almost 50% of the
302+
# run time in this loop so we avoid it if
303+
# there is no read timeout.
304+
async with async_timeout.timeout(receive_timeout):
305+
msg = await self._reader.read()
306+
else:
298307
msg = await self._reader.read()
299308
self._reset_heartbeat()
300309
finally:

aiohttp/web_ws.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,7 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
484484

485485
loop = self._loop
486486
assert loop is not None
487+
receive_timeout = timeout or self._receive_timeout
487488
while True:
488489
if self._waiting:
489490
raise RuntimeError("Concurrent call to receive() is not allowed")
@@ -499,7 +500,14 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
499500
try:
500501
self._waiting = True
501502
try:
502-
async with async_timeout.timeout(timeout or self._receive_timeout):
503+
if receive_timeout:
504+
# Entering the context manager and creating
505+
# Timeout() object can take almost 50% of the
506+
# run time in this loop so we avoid it if
507+
# there is no read timeout.
508+
async with async_timeout.timeout(receive_timeout):
509+
msg = await self._reader.read()
510+
else:
503511
msg = await self._reader.read()
504512
self._reset_heartbeat()
505513
finally:

0 commit comments

Comments
 (0)