git worktree cho phép checkout nhiều branches vào các thư mục riêng biệt, cùng chia sẻ 1 git object store — không cần clone lần 2.
Khi stash không đủ:
- Đang code feature phức tạp → urgent hotfix cần làm ngay → stash feature, switch, code hotfix, unstash → context switching overhead cao.
- Clone lần 2: tốn disk, download lại tất cả objects.
Worktree solution:
# Thêm worktree cho hotfix trong thư mục riêng:
git worktree add ../my-repo-hotfix hotfix/critical-bug
# hoặc tạo branch mới:
git worktree add -b hotfix/urgent ../my-repo-hotfix main
# Làm việc trong thư mục hotfix:
cd ../my-repo-hotfix
# Code, test, commit — hoàn toàn độc lập
# Xóa worktree sau khi xong:
git worktree remove ../my-repo-hotfixƯu điểm:
- Chia sẻ git objects → không tốn disk thêm
- Không phải stash/unstash
- Build artifacts của mỗi worktree độc lập (2 terminal chạy npm run dev đồng thời)
Hạn chế: 1 branch chỉ có thể được checkout trong 1 worktree tại 1 thời điểm.
Ideal use case: monorepo, cần chạy 2 versions đồng thời để compare behavior.
git worktree lets you check out multiple branches into separate directories that all share one git object store — no second clone needed.
When stash is not enough:
- You are deep in a complex feature → urgent hotfix arrives → stash feature, switch, code hotfix, unstash → high context-switching overhead.
- Second clone: wastes disk space and re-downloads all objects.
Worktree solution:
# Add a worktree for the hotfix in a separate directory:
git worktree add ../my-repo-hotfix hotfix/critical-bug
# Or create a new branch:
git worktree add -b hotfix/urgent ../my-repo-hotfix main
# Work in the hotfix directory:
cd ../my-repo-hotfix
# Code, test, commit — completely independent
# Remove worktree when done:
git worktree remove ../my-repo-hotfixAdvantages:
- Shared git objects → no extra disk space
- No stash/unstash context switching
- Each worktree has independent build artifacts (run npm run dev in two terminals simultaneously)
Limitation: one branch can only be checked out in one worktree at a time.
Ideal use case: monorepos, running two versions simultaneously to compare behavior.