How Text Diff Works: Comparing Lines, Words and Characters
A diff shows the smallest set of changes that turns one text into another. Knowing how it works helps you read diffs and avoid noisy comparisons.
The idea behind diff
A diff algorithm finds what two texts have in common, in the same order: the longest common subsequence. Everything outside it is reported as removed (from the old text) or added (in the new text). A change to a line is usually shown as one deletion plus one insertion.
The widely used Myers algorithm (1986) finds a shortest edit script, meaning the fewest insertions and deletions. It is the default in Git.
Line, word and character granularity
- Line diffs are best for code and configuration files, and are what version control uses.
- Word diffs suit prose, where a single edited word would otherwise mark a whole paragraph as changed.
- Character diffs pinpoint typos, changed digits or swapped letters inside a line.
Good tools combine them: line-level alignment, then highlighting the exact words or characters that changed within modified lines.
Reading a unified diff
The @@ header gives the starting line and line count in the old (-) and new (+) versions. Lines starting with a space are unchanged context.
Why you see changes you can't see
- Line endings: Windows uses CRLF, macOS and Linux use LF. A file saved on another system can show every line as changed.
- Trailing whitespace and tabs vs spaces look identical on screen but are different characters.
- Reformatting (a code formatter or rewrapped paragraphs) shifts many lines at once.
Most diff tools can ignore whitespace or line-ending differences; turn that on when you only care about content.
Comparing JSON
For JSON, format both sides the same way first (same indentation and, ideally, sorted keys). Otherwise identical data in a different order will look like a large change.