⚡️ Speed up method SyncCursorPage.next_page_info by 933%
#44
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.
📄 933% (9.33x) speedup for
SyncCursorPage.next_page_infoinsrc/openai/pagination.py⏱️ Runtime :
211 microseconds→20.4 microseconds(best of138runs)📝 Explanation and details
The optimized code achieves a 933% speedup by eliminating an expensive
isinstancecheck and unnecessary type casting.Key optimizations:
Removed
cast(Any, data[-1]): The original code unnecessarily cast the last item toAny, which adds runtime overhead without providing any functional benefit since we only need to check for theidattribute.Replaced
isinstance(item, CursorPageItem)withhasattr(item, "id"): Theisinstancecheck was the primary bottleneck (90% of execution time in the profiler). Usinghasattrleverages Python's duck typing approach - we only care if the object has anidattribute, not its exact type. This is much faster than class hierarchy checking.Used
getattr(item, "id", None)for safe attribute access: This provides the same null-checking behavior asitem.id is Nonebut works safely with any object type.Performance impact by test case type:
isinstancecheck that always failedThe optimization maintains identical behavior while being much more efficient for Python's dynamic typing model.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SyncCursorPage.next_page_info-mhdiwirfand push.