⚡️ Speed up method WebSocket.receive by 6%
#2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 6% (0.06x) speedup for
WebSocket.receiveinstarlette/websockets.py⏱️ Runtime :
2.49 milliseconds→2.35 milliseconds(best of131runs)📝 Explanation and details
The optimization achieves a 6% runtime improvement and 4% throughput increase by restructuring the conditional logic in the WebSocket's
receivemethod to reduce branching overhead and improve CPU instruction flow.Key optimizations applied:
Eliminated elif chain: Changed
elif self.client_state == WebSocketState.CONNECTED:to a separateifstatement, reducing nested branching that can hurt CPU branch prediction.Optimized hot path for CONNECTED state: In the CONNECTED state (the most frequent case based on profiler data showing 3,747 hits), the code now uses two separate
ifstatements for message type checking instead of a combinednot incheck followed by anotherif. This creates a more direct execution path:websocket.disconnect(less common, ~203 hits)websocket.receive(most common, ~3,540 hits)Reduced computational overhead: The original code used
message_type not in {"websocket.receive", "websocket.disconnect"}which requires set membership testing, followed by anothermessage_type == "websocket.disconnect"check. The optimized version eliminates the set lookup and performs direct string comparisons.Performance impact by test type:
The line profiler confirms that the CONNECTED state processing (lines handling
message_typechecks) shows reduced execution time, directly contributing to the overall throughput improvement of ~20,000 additional operations per second.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-WebSocket.receive-mhbh4b0pand push.