⚡️ Speed up method HTTPEndpoint.method_not_allowed by 7%
#6
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.
📄 7% (0.07x) speedup for
HTTPEndpoint.method_not_allowedinstarlette/endpoints.py⏱️ Runtime :
3.67 milliseconds→3.42 milliseconds(best of164runs)📝 Explanation and details
The optimization achieves a 7% runtime improvement by precomputing expensive string operations that were previously executed on every
method_not_allowedcall.What changed:
", ".join(self._allowed_methods)operation is moved from the hot path inmethod_not_allowedto the initialization phase, stored as_allowed_methods_str{"Allow": ...}is created once during__init__as_method_not_allowed_headersinstead of being recreated on each method callWhy this is faster:
Performance impact by test case:
The 2.5% throughput improvement (279,680 → 286,672 ops/sec) demonstrates better request processing capacity, making this optimization particularly valuable for high-traffic web applications where
method_not_allowedresponses are frequent.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-HTTPEndpoint.method_not_allowed-mhbj2l5wand push.