0
0
Gitdevops~5 mins

Worktrees vs stashing decision in Git - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Worktrees vs stashing decision
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of changed files or size of changes grows:

Input Size (changed files)Approx. Operations (stash)
10Quick compress and decompress
100Noticeable delay saving and applying stash
1000Longer time compressing and applying stash
Input Size (repo size)Approx. Operations (worktree)
10 filesQuick directory setup with links
100 filesStill fast due to linking, minimal copying
1000 filesSetup 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how git operations scale helps you explain your choices clearly and shows you think about efficiency, a valuable skill in real projects.

Self-Check

What if we changed from using git stash to git stash with patch mode? How would the time complexity change?