⚡ Optimize WebSocket masking via integer conversion - #5
Conversation
Replaced the slow Python-level `for` loop for WebSocket masking with a highly optimized method that utilizes Python's arbitrary-precision integers (`int.from_bytes(sys.byteorder)`). For both `ws_encode` and `ws_decode`, large payloads are now masked/unmasked almost 20x faster than the original implementation. Co-authored-by: maattyi <228237318+maattyi@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
💡 What: The
forloop that iterates over every byte of the payload to apply the WebSocket XOR mask has been replaced with Python's large integer arithmetic functionality. The code converts the payload and a duplicated mask into integers usingint.from_bytes, XORs them directly, and converts the result back to bytes.🎯 Why: The original implementation utilized a Python loop over
bytearray. This was highly inefficient due to the overhead of the Python virtual machine stepping through every single byte of data. By shifting this work to Python's internal C implementation of big integers, we drastically reduce execution time and computational overhead.📊 Measured Improvement:
We utilized a custom script (
bench5.py) usingtimeitfor 100 runs on a 1MB payload and 10000 runs on a 1KB payload.1MB Payload:
1KB Payload:
The changes ensure functionally identical output. Edge cases (like empty payloads and unmasked frames) are well handled.
PR created automatically by Jules for task 11243390841297451717 started by @maattyi