⚡️ Speed up function parse_req_python_version by 78% #123
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.
📄 78% (0.78x) speedup for
parse_req_python_versioninsrc/black/files.py⏱️ Runtime :
19.5 milliseconds→10.9 milliseconds(best of116runs)📝 Explanation and details
The optimization adds a fast-path string parsing for common Python version strings before falling back to the expensive
Versionobject construction.Key Changes:
Version()constructor3.xformat), falling back to original logic for complex version strings (pre-releases, epochs, etc.)Why It's Faster:
The profiler shows
Version(requires_python)consumed 78% of runtime (51.9ms out of 66.6ms total). The optimization bypasses this for simple cases:startswith,split,isdigit) are much faster than full version parsingTargetVersion(int(parts[1]))is significantly cheaper than accessingversion.release[1]after full parsingPerformance Characteristics:
The optimization targets the dominant use case while preserving all edge case handling, making it highly effective for typical Python version parsing workloads.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-parse_req_python_version-mgsu0caland push.