Removing worktrees in Git - Time & Space Complexity
When removing git worktrees, it's important to understand how the time taken grows as you remove more worktrees.
We want to know how the number of operations changes when deleting worktrees from a repository.
Analyze the time complexity of the following git commands to remove a worktree.
git worktree remove <path>
# git worktree prune (for stale worktrees)
git worktree prune
This code removes a linked worktree directory and cleans up references in the main repository.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the list of all registered worktrees in the repository.
- How many times: Once per worktree entry during removal or pruning.
As the number of worktrees increases, git must check each one to remove or prune it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The operations grow linearly with the number of worktrees.
Time Complexity: O(n)
This means the time to remove worktrees grows directly in proportion to how many worktrees exist.
[X] Wrong: "Removing a worktree is always instant regardless of how many worktrees exist."
[OK] Correct: Git must check all worktrees to update references, so more worktrees mean more work.
Understanding how git commands scale with repository size helps you reason about performance and system behavior in real projects.
"What if git cached worktree info to remove a single worktree without scanning all others? How would the time complexity change?"