⚡️ Speed up function select_first_detection by 44%
#776
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.
📄 44% (0.44x) speedup for
select_first_detectionininference/core/workflows/core_steps/common/query_language/operations/detections/base.py⏱️ Runtime :
160 microseconds→111 microseconds(best of53runs)📝 Explanation and details
The optimization replaces
deepcopy(detections)withtype(detections)()for empty detections, delivering a 44% speedup by eliminating expensive deep copy operations on empty containers.Key changes:
deepcopyimport (no longer needed)return deepcopy(detections)toreturn type(detections)()for empty casesreturn detections[0])Why this is faster:
The line profiler shows
deepcopy(detections)took 164,758ns (33.8% of total time) in the original vs just 7,960ns (2.5% of total time) fortype(detections)()in the optimized version. Deep copying involves recursive traversal of object structures and memory allocation even for empty containers, whiletype(detections)()simply instantiates a new empty object of the same class.Performance impact by test case:
This optimization is particularly valuable for workflows that frequently encounter empty detection results, providing substantial performance gains without changing behavior or breaking existing code contracts.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-select_first_detection-miqhigy0and push.