Listing worktrees in Git - Time & Space Complexity
When using Git, listing worktrees shows all linked working directories. Understanding how the time to list worktrees grows helps us know how fast this command runs as projects grow.
We want to know how the command's work changes as the number of worktrees increases.
Analyze the time complexity of the following Git command.
git worktree list
This command lists all the worktrees linked to the current Git repository.
Look for repeated steps the command does internally.
- Primary operation: Iterating over each worktree entry stored in the repository metadata.
- How many times: Once for each worktree configured (n times).
The command reads and processes each worktree entry one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads and prints |
| 100 | 100 reads and prints |
| 1000 | 1000 reads and prints |
Pattern observation: The work grows directly with the number of worktrees; doubling worktrees doubles the work.
Time Complexity: O(n)
This means the time to list worktrees grows linearly with how many worktrees exist.
[X] Wrong: "Listing worktrees is instant no matter how many worktrees there are."
[OK] Correct: The command must read each worktree's info, so more worktrees mean more work and time.
Understanding how commands scale with input size shows you can reason about tool performance, a useful skill in real projects and interviews.
"What if the worktree info was cached in a single file? How would that affect the time complexity?"