⚡️ Speed up function _completion_installed by 16%
#4
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.
📄 16% (0.16x) speedup for
_completion_installedinpdd/cli.py⏱️ Runtime :
630 microseconds→541 microseconds(best of41runs)📝 Explanation and details
The optimized code achieves a 16% speedup through three key optimizations:
1. Dictionary-based shell RC path lookup - Replaced the
if/elifchain inget_shell_rc_path()with a dictionary mapping (_SHELL_RC_PATHS). This eliminates multiple string comparisons and only callsos.path.expanduser("~")when a valid shell is found, rather than always calling it upfront.2. Binary file reading for string searches - The most significant optimization in
_completion_installed()switches fromPath.read_text()toPath.read_bytes()for the initial file read. Since we're searching for ASCII strings ("PDD CLI completion" and "pdd_completion"), searching in binary content usingb"PDD CLI completion" in contentis faster than Unicode string operations. The code gracefully falls back to text reading only if binary reading fails.3. Early path validation - Added
len(rc_path) < 3check to quickly reject obviously invalid paths before attempting file operations.Performance characteristics based on test results:
The optimizations maintain identical behavior and error handling while leveraging Python's efficient binary operations for the common case of searching ASCII text in configuration files.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_completion_installed-mgmo1zgeand push.