⚡️ Speed up method FileUploadProgress.is_done by 11%
#25
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.
📄 11% (0.11x) speedup for
FileUploadProgress.is_doneingradio/route_utils.py⏱️ Runtime :
19.1 microseconds→17.2 microseconds(best of51runs)📝 Explanation and details
The optimization replaces a defensive check-then-access pattern with a try-except approach that follows Python's "Easier to Ask for Forgiveness than Permission" (EAFP) principle.
Key Changes:
upload_id not in self._statuses, then accessingself._statuses[upload_id].is_doneself._statuses[upload_id].is_doneand catches theKeyErrorif the key doesn't existWhy This Is Faster:
Dictionary membership testing (
inoperator) and key access both require hash computation and potential collision resolution. The original approach does this twice for existing keys, while the optimized version does it only once. For the common case whereupload_idexists (which appears to be ~82% of calls based on the profiler showing 41 successful accesses vs 9 exceptions), this eliminates unnecessary work.Performance Impact:
The test results show consistent 5-25% speedups across most scenarios, with particularly strong gains (up to 75% faster) in large-scale tests where hash table efficiency matters most. The optimization is especially effective when the dictionary contains many entries, as hash collision resolution becomes more expensive. Exception cases show minimal overhead since
KeyErrorhandling is highly optimized in Python's C implementation.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-FileUploadProgress.is_done-mhanqfkcand push.