What is a branch in Git and why is it cheap?
Model answer
A branch is a movable pointer to a commit. In the repository it is just a small file such as .git/refs/heads/main that holds a 40-character commit hash. Creating a branch writes that one file; no project files are copied.
When you commit on a branch, Git creates the new commit and moves the pointer forward. HEAD tells Git which branch is current.
git branch feature/login # create
git switch feature/login # move HEAD to it
git switch -c feature/search # create and switch
Because branches cost almost nothing, the normal workflow is to create one per task or fix, work in isolation, and merge it back through a pull request. Branching and switching take milliseconds even in large repositories.
A branch is only a label; deleting one does not delete the commits, as long as another ref reaches them.
Takeaway: branch freely, one per piece of work.
Key points
- A branch is a pointer to a commit
- Stored as a tiny file with a hash
- No files are copied when branching
- One branch per task is the normal workflow
Likely follow-ups
- What happens to commits when you delete a branch?
- What is the difference between a branch and a tag?
Common mistakes
- Thinking a branch is a full copy of the project
- Avoiding branches because they feel heavy