Rebase vs Merge

A common git branching strategy is for developers to work on the develop branch and then create feature branches. Feature branches can be short-lived or long-lived. When using a long-lived feature branch you will need to use git to keep the branch in sync with the remote branch. There are two techniques for doing this: rebasing and merging.

Merging

This is the safe option. When you type git merge develop you are merging all of the new changes on develop into your feature branch. You will get a single merge commit which is a representation of all the new changes.

Rebasing

The drawback to merging is that if you merge frequently you end up with lots of merge commits. This litters your git history. It can also make it harder to see which commit introduced a certain change.

The solution is to rebase. Rebasing is a descructive action because it re-writes your git history. It creates brand new commits, on your feature branch, for all the new commits on develop. Then it puts all of your new feature commits on top of that.

After the rebase you will have all of your feature branch commits on top of the latest develop.

Another feature of rebasing is that each commit is merged individually. This is a benefit because conflicts are dealt with in smaller chunks. It’s also a drawback because you may have to merge commits which are removed in a subsequent commit and are no longer in the code base! If you have a feature branch with hundreds of commits, rebasing can be a painful process.

Warning

Remember that rebasing is a descructive operation. When you push your branch back to GitHub you will need to force push because you have re-written history.

This technique works well on private branches (like feature branches) but shouldn’t be used on public branches (like develop). Rebasing develop will cause all other developers on your team to rebase because their branch will be out of date.