Worktrees vs stashing decision in Git - Performance Comparison
When deciding between using git worktrees or stashing changes, it's important to understand how the time to complete these actions grows as your project size or number of changes increases.
We want to know how the effort and time scale when switching contexts with worktrees versus stashing.
Analyze the time complexity of these git commands:
# Using stash
$ git stash save "WIP changes"
$ git checkout other-branch
$ git stash pop
# Using worktree
$ git worktree add ../other-branch-dir other-branch
# Work in new directory without affecting current one
This snippet shows saving changes with stash and switching branches versus creating a new worktree for parallel work.
Look at what repeats or scales with input size:
- Primary operation: Saving and applying changes (stash) or creating a new worktree directory.
- How many times: Each stash save/pop involves compressing and decompressing changes; worktree creation involves linking files once.
As the number of changed files or size of changes grows:
| Input Size (changed files) | Approx. Operations (stash) |
|---|---|
| 10 | Quick compress and decompress |
| 100 | Noticeable delay saving and applying stash |
| 1000 | Longer time compressing and applying stash |
| Input Size (repo size) | Approx. Operations (worktree) |
|---|---|
| 10 files | Quick directory setup with links |
| 100 files | Still fast due to linking, minimal copying |
| 1000 files | Setup time grows slowly, mostly filesystem metadata operations |
Pattern observation: Stashing time grows with change size because of compression work; worktree setup grows slowly with repo size due to filesystem operations.
Time Complexity: O(n)
This means the time to stash or create a worktree grows roughly in direct proportion to the number of changed files or repo size.
[X] Wrong: "Stashing is always faster than creating a worktree regardless of project size."
[OK] Correct: Stashing involves compressing changes which can slow down as changes grow, while worktrees mostly create links and metadata, often faster for large projects.
Understanding how git operations scale helps you explain your choices clearly and shows you think about efficiency, a valuable skill in real projects.
What if we changed from using git stash to git stash with patch mode? How would the time complexity change?