Diff (short for "difference") is the foundation of version control, code review, and collaboration. Every Git commit, pull request, and merge operation relies on diff algorithms to identify what changed between two versions of a file. Understanding how diffs work makes you a more effective developer.
Unified Diff Format
The unified diff format (produced by diff -u and git diff) is the modern standard:
- Lines starting with
---and+++identify the old and new files @@hunk headers show line ranges:@@ -10,7 +10,8 @@- Lines starting with
-were removed - Lines starting with
+were added - Lines starting with a space are unchanged context (typically 3 lines before and after)
Diff Algorithms
| Algorithm | Speed | Quality | Best For |
|---|---|---|---|
| Myers | Fast | Minimal edit distance | Default (Git's standard) |
| Patience | Moderate | Better with moved blocks | Refactored code |
| Histogram | Fast | Improved patience | General use (recommended) |
| Minimal | Slow | Guaranteed smallest diff | When diff size matters |
Reading a Hunk Header
The hunk header @@ -10,7 +10,8 @@ breaks down as:
-10,7— Original file: start at line 10, show 7 lines+10,8— Modified file: start at line 10, show 8 lines- The difference (8 - 7 = 1) tells you one line was added in this hunk
Three-Way Merge
A three-way merge uses three inputs: the base (common ancestor), ours (local changes), and theirs (remote changes):
- Changes in only one branch are auto-merged
- Changes to different parts of the same file are auto-merged
- Changes to the same lines in both branches create a conflict
- Without the base, the tool can't tell which changes are new — this is why Git needs the merge base
Merge Conflict Markers
When Git can't auto-merge, it inserts conflict markers:
<<<<<<< HEAD— start of your changes=======— separator between versions>>>>>>> feature-branch— end of their changes
Resolve by editing the file to keep the correct version, removing all markers, then staging the file.
Creating and Applying Patches
- Create:
git diff > changes.patchorgit format-patch HEAD~3 - Apply:
git apply changes.patchorpatch -p1 < changes.patch - Check first:
git apply --check changes.patchto verify without applying git format-patchincludes commit metadata (author, message) — useful for email-based workflows
Diff in Code Review
- Review hunks, not files — focus on individual changes in context
- Use word-level diff (
git diff --word-diff) for prose and config files - Ignore whitespace (
git diff -w) when reviewing logic changes mixed with formatting - Stat summary (
git diff --stat) to see the scope before diving in
💡 Pro Tip: Use
git diff --diff-algorithm=histogram for more readable diffs, especially when code has been moved or reorganized. You can set it as your default: git config --global diff.algorithm histogram.