⚡️ Speed up function sorter
by 17%
#94
Open
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.
📄 17% (0.17x) speedup for
sorter
insrc/async_examples/concurrency.py
⏱️ Runtime :
691 milliseconds
→590 milliseconds
(best of27
runs)📝 Explanation and details
The optimized code implements two key improvements to the bubble sort algorithm:
1. Early termination with swap detection: Added a
swapped
flag that tracks whether any swaps occurred during a pass. If no swaps happen, the array is already sorted and the algorithm exits early viabreak
. This is particularly effective for already-sorted or nearly-sorted inputs.2. Reduced comparison range: Changed the inner loop from
range(len(arr) - 1)
torange(len(arr) - 1 - i)
. After each outer loop iteration, the largesti
elements are guaranteed to be in their final positions at the end of the array, so we don't need to check them again.Performance impact: The line profiler shows the inner loop iterations dropped from 2.3M to 1.1M (52% reduction), and overall runtime improved by 17%. The optimizations are most effective for:
These changes maintain identical sorting behavior and async functionality while dramatically reducing unnecessary work, especially evident in test cases with ordered or semi-ordered data.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-mfbuuwpo
and push.