⚡️ Speed up function polygon_to_bbox by 87%
#9
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.
📄 87% (0.87x) speedup for
polygon_to_bboxindoctr/utils/geometry.py⏱️ Runtime :
805 microseconds→430 microseconds(best of412runs)📝 Explanation and details
The optimization replaces the original
zip(*polygon)approach with a single-pass iterator-based algorithm that eliminates intermediate data structure allocations and reduces function call overhead.Key optimizations:
Eliminates
zip(*polygon)overhead: The original creates two temporary tuples containing all x and y coordinates, which requires memory allocation and unpacking operations. The optimized version processes coordinates directly without intermediate collections.Single-pass min/max computation: Instead of calling
min()andmax()functions (which internally iterate through the data), the optimized version computes all four values (min_x, max_x, min_y, max_y) in one iteration using simple comparison operations.Reduces function call overhead: The original makes 4 function calls (
min(x),min(y),max(x),max(y)), while the optimized version uses direct comparisons that are faster than function calls in Python.Performance characteristics based on test results:
The optimization is particularly effective for larger polygons where memory allocation costs and multiple iterations become significant bottlenecks.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
common/test_utils_geometry.py::test_polygon_to_bbox🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-polygon_to_bbox-mg7s2g9eand push.