Skip to content

Commit

Permalink
[PR #6967/179312ea backport][3.9] Compute XOR table lazily (#7105)
Browse files Browse the repository at this point in the history
**This is a backport of PR #6967 as merged into master
(179312e).**

This speeds up import time by a little bit:
```
In [2]: %timeit [bytes(a ^ b for a in range(256)) for b in range(256)]
8.41 ms ± 656 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
```
This is about 5% of aiohttp's import time

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
  • Loading branch information
patchback[bot] and hauntsaninja authored Nov 28, 2022
1 parent f81cd7f commit 5971d43
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion aiohttp/http_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
import collections
import functools
import json
import random
import re
Expand Down Expand Up @@ -121,7 +122,9 @@ class WSHandshakeError(Exception):


# Used by _websocket_mask_python
_XOR_TABLE: Final[List[bytes]] = [bytes(a ^ b for a in range(256)) for b in range(256)]
@functools.lru_cache()
def _xor_table() -> List[bytes]:
return [bytes(a ^ b for a in range(256)) for b in range(256)]


def _websocket_mask_python(mask: bytes, data: bytearray) -> None:
Expand All @@ -141,6 +144,7 @@ def _websocket_mask_python(mask: bytes, data: bytearray) -> None:
assert len(mask) == 4, mask

if data:
_XOR_TABLE = _xor_table()
a, b, c, d = (_XOR_TABLE[n] for n in mask)
data[::4] = data[::4].translate(a)
data[1::4] = data[1::4].translate(b)
Expand Down

0 comments on commit 5971d43

Please sign in to comment.