⚡️ Speed up function is_valid_cidr by 23%
#37
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.
📄 23% (0.23x) speedup for
is_valid_cidrinsrc/requests/utils.py⏱️ Runtime :
1.66 milliseconds→1.34 milliseconds(best of193runs)📝 Explanation and details
The optimization replaces inefficient string operations with a single, more efficient parsing approach:
Key Changes:
.count("/")+ multiple.split("/")calls with.partition('/'): The original code callsstring_network.split("/")twice - once to extract the mask and once to extract the IP address. The optimized version usespartition('/')which splits the string into exactly three parts (before slash, slash, after slash) in a single operation.Why This is Faster:
.partition()scans the string once and returns all needed components, while the original approach scans multiple times with.count()and.split()..split("/")creates a new list each time it's called, whereas.partition()creates a single tuple with fixed size.sep != '/'directly validates the slash presence instead of counting occurrences.Performance Characteristics:
The optimization shows consistent 20-30% speedups across most test cases, particularly excelling with:
The optimization maintains identical behavior and error handling while reducing string processing overhead, making it especially beneficial for applications that validate many CIDR strings.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_utils.py::TestIsValidCIDR.test_invalidtest_utils.py::TestIsValidCIDR.test_valid🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-is_valid_cidr-mgpwicoyand push.