⚡️ Speed up function matrix_sum by 50%
#60
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.
📄 50% (0.50x) speedup for
matrix_suminsrc/dsa/various.py⏱️ Runtime :
27.0 milliseconds→18.0 milliseconds(best of61runs)📝 Explanation and details
The optimization eliminates redundant computation by using Python's walrus operator (
:=) to compute each row sum only once instead of twice.Key optimization: The original code calls
sum(matrix[i])twice for each row - once in the conditionif sum(matrix[i]) > 0and again in the list comprehension[sum(matrix[i]) for i in range(len(matrix))]. The optimized version uses the walrus operator(row_sum := sum(row))to compute the sum once, store it inrow_sum, and reuse it in both the condition and the result list.Additional improvements:
matrixinstead ofrange(len(matrix))eliminates index lookupsWhy this leads to speedup: The optimization reduces time complexity from O(2nm) to O(nm) where n is the number of rows and m is the average row length, since each element is now summed only once instead of twice. This is particularly effective for larger matrices, as shown in the test results where large-scale tests show 80-99% speedups.
Test case performance patterns:
The optimization is most beneficial for matrices with many rows that pass the positive sum filter, where the double computation penalty is most pronounced.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-matrix_sum-mdpc58n8and push.