⚡️ Speed up function get_patches_dir_for_project by 112% in PR #690 (worktree/persist-optimization-patches)
#704
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.
⚡️ This pull request contains optimizations for PR #690
If you approve this dependent PR, these changes will be merged into the original PR branch
worktree/persist-optimization-patches.📄 112% (1.12x) speedup for
get_patches_dir_for_projectincodeflash/code_utils/git_worktree_utils.py⏱️ Runtime :
137 microseconds→64.5 microseconds(best of5runs)📝 Explanation and details
The optimization achieves a 112% speedup through two key changes:
Replace
list(repo.iter_commits(...))withnext(repo.iter_commits(...)): The original code materializes all root commits into a list just to access the first one. The optimized version usesnext()to get only the first commit from the iterator, avoiding unnecessary memory allocation and iteration through all root commits. This is particularly beneficial for repositories with multiple root commits (though rare, they can occur in merged repositories).Remove redundant
Path()wrapper: The original code wrapspatches_dir / project_idinPath(), but sincepatches_diris already aPathobject and the/operator returns aPath, the wrapper is unnecessary overhead.The test results show consistent speedups across all scenarios (93-159% faster), with the optimization being especially effective for repositories with many commits (500 commits: 18.0μs → 9.09μs) and complex structures (unusual branches: 16.2μs → 8.28μs). The
next()optimization provides the most significant performance gain since it eliminates the need to create intermediate list objects and stops iteration immediately after finding the first commit.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-pr690-2025-09-02T21.53.21and push.