Development

What diff algorithms are available and which should I use?

Different diff algorithms produce different results with different performance characteristics. Learn about available algorithms and how to choose the best one for your needs.

By Inventive HQ Team

Understanding Diff Algorithms

A diff algorithm is the method a comparison tool uses to identify the minimum set of changes between two versions of a file, and Git ships four of them — myers (the default), minimal, patience, and histogram — selectable with git diff --diff-algorithm=<name> or the diff.algorithm config key. Myers and minimal optimize for the fewest changed lines; patience and histogram optimize for human-readable output by anchoring the comparison on lines that appear exactly once, which keeps moved and reordered code blocks intact instead of scrambling them. For most code review, histogram is the best choice — it produces the cleanest diffs on refactored code and runs about as fast as the default.

That is the summary an AI Overview gives you. What it can't give you is the side-by-side of why the same two files produce different-looking diffs under each engine, a working command reference you can paste, and a tool to feel the difference yourself. That's below.

Diff algorithms are the mathematical engines behind diff tools, determining how differences are identified and displayed. While end users typically don't think about which algorithm is being used, understanding the available algorithms and their trade-offs helps you choose the right diff tool and interpret results correctly.

Different algorithms use different strategies to identify differences, leading to different results with different computational costs. The choice of algorithm affects both the quality of results and the speed of comparison.

Git's Four Diff Algorithms Compared

Everything you can select in Git lives in this table. This is the decision surface — pick a row, run the command, move on.

AlgorithmHow it worksStrengthsWhen to use
myers (default)Finds the shortest edit script — the fewest line insertions/deletions to turn file A into file B. Runs in O(ND) time.Minimal change count; fast for small edits; universally compatible; predictable.The default. Use when you want maximum compatibility or don't care about diff shape.
minimalMyers, but spends extra time guaranteeing the absolute smallest possible diff.Smallest diff by line count; removes spurious edits Myers may leave.When diff size matters more than speed — e.g. generating a clean patch for review.
patienceMatches only lines that appear exactly once in both files first, then recurses into the gaps between those anchors.Keeps moved/reordered blocks intact; readable diffs on refactors; avoids "slid" hunk boundaries.When a Myers diff looks scrambled — reordered functions, moved imports, shifted braces.
histogramA refinement of patience that also scores lines by frequency to pick better anchors, faster.Patience-quality readability with better speed on large files; best all-round for code.The recommended everyday choice for code review. Set it globally and forget it.

Set your preference once:

# Recommended for code review
git config --global diff.algorithm histogram

# Or per-invocation (overrides config)
git diff --diff-algorithm=patience file.js

# Shortcut flags exist for three of them
git diff --histogram
git diff --patience
git diff --minimal
How Myers and histogram diff a reordered code block The same reordered file shown two ways: Myers marks the whole block changed, while histogram anchors on the unique moved line and keeps the rest unchanged. Same reordered file, two algorithms

myers (default) - function gamma() { } - function alpha() { } + function alpha() { } + function beta() { } + function gamma() { } 5 lines churned

histogram + function gamma() { } function alpha() { } function beta() { } - function gamma() { } 1 line moved, 2 unchanged

unique line = anchor

The Classic Longest Common Subsequence (LCS) Algorithm

How LCS Works

The Longest Common Subsequence algorithm finds the longest sequence of items that appears in both files in the same order:

  1. Compare all possible subsequences in both files
  2. Find the longest subsequence appearing in both
  3. Lines not in the LCS are differences
  4. Display what was added, removed, and kept

LCS guarantees finding the minimal-change diff, meaning fewest lines marked as different.

Advantages of LCS

  • Optimal results: Minimizes the number of differences shown
  • Predictable: Always produces the same result for the same input
  • Mathematically sound: Provably correct approach

Disadvantages of LCS

  • Slow: O(n×m) time complexity where n and m are file sizes
  • Memory intensive: Requires storing comparison data for all possible subsequences
  • Not practical for large files: Becomes unusably slow with files over ~1000 lines

When to Use LCS

LCS is suitable for:

  • Small files (under 1000 lines)
  • When guaranteed optimal results are important
  • Academic or research purposes
  • When performance is less critical than correctness

Most practical diff tools have moved away from pure LCS due to performance limitations.

The Myers Algorithm (Diff Algorithm)

Advertisement

How Myers Algorithm Works

Myers algorithm finds the shortest "edit script" with fewer operations required:

  1. Creates a search space of possible edit paths
  2. Explores the space to find shortest path to make files identical
  3. Unlike LCS, focuses on minimal edits rather than longest common sequence
  4. More efficient exploration reduces unnecessary comparisons

Advantages of Myers

  • Faster than LCS: O(min(n, m) × d) where d is the number of differences
  • Practical for large files: Works efficiently on real-world file sizes
  • Better for version control: Produces intuitive results for code changes
  • Still optimal: Produces minimal-change diffs when differences are small
  • Industry standard: Used by Git and most modern diff tools

Disadvantages of Myers

  • More complex: Harder to understand than naive approaches
  • Still slow for very different files: Degrades when files differ significantly

When to Use Myers

Myers algorithm is suitable for:

  • Most real-world use cases
  • Version control systems (Git uses this)
  • Code comparison
  • Files of any practical size
  • When both correctness and performance matter

Git's diff command and most modern tools default to Myers or variants.

Patience Algorithm

How Patience Algorithm Works

Patience algorithm uses a different approach inspired by card game solitaire:

  1. Lines with unique tokens are matched first (patience matching)
  2. Builds blocks of matching content
  3. Recursively applies algorithm to unmatched regions
  4. Identifies semantically meaningful changes

Advantages of Patience

  • Better for code: Produces more intuitive results for source code changes
  • Handles refactoring better: Recognizes when code blocks move
  • Faster for certain patterns: Efficient when files have repeated sections
  • Semantically meaningful: Changes make more sense to humans

Disadvantages of Patience

  • Not optimal: May not find absolute minimum differences
  • Less predictable: Results depend on content, not just structure
  • More opinionated: Biases results toward certain interpretations

When to Use Patience

Patience algorithm is excellent for:

  • Code comparison and review
  • Understanding refactoring changes
  • Making diffs more human-readable
  • Files with repeated content blocks
  • Finding semantic changes rather than literal differences

Histogram Algorithm

How Histogram Works

Histogram algorithm is a refinement of patience algorithm:

  1. Creates frequency histograms of lines
  2. Matches lines with unique or rare tokens first
  3. Recursively processes remaining lines
  4. More efficient than patience for large files

Advantages of Histogram

  • Efficient: Faster than patience while maintaining similar results
  • Handles large files: Works well on substantial codebases
  • Good heuristic: Produces human-sensible results
  • Performance optimized: Uses memory-efficient data structures

Disadvantages of Histogram

  • Heuristic-based: Not guaranteed optimal
  • Content dependent: Results vary based on actual file content

When to Use Histogram

Histogram is ideal for:

  • Large source code files
  • When performance and readability matter equally
  • Production version control systems
  • Git can use histogram: git diff --histogram

Git's histogram algorithm is an optimized variant used in practice for better performance.

Other Specialized Algorithms

Unified Diff Format Algorithm

Not a comparison algorithm but a representation format that can work with various backends:

  • Shows differences with context lines
  • Standard format understood across tools
  • Used in patch files
  • Can be generated by multiple algorithms

Split View Algorithm

Not an algorithm itself but a display strategy:

  • Shows original on left, modified on right
  • Highlights differences in both versions
  • User alignment of changed sections
  • More visual than text-based diffs

Practical Algorithm Selection

For Git Users

Configure your preferred algorithm:

# Use patience algorithm
git config --global diff.algorithm patience

# Use histogram algorithm (recommended for performance)
git config --global diff.algorithm histogram

# Use Myers (default)
git config --global diff.algorithm myers

Git also supports:

  • default - Myers algorithm
  • myers - Myers algorithm explicitly
  • minimal - Myers with minimal diff size
  • patience - Patience algorithm
  • histogram - Histogram algorithm

For Online Diff Tools

Most online diff tools support:

  • Myers: Standard for compatibility
  • Patience: Better for code
  • Histogram: Balanced performance/quality

Check your tool's documentation for options.

Decision Tree for Algorithm Selection

  1. Performance critical and large files? → Use Histogram
  2. Code comparison and readability important? → Use Patience or Histogram
  3. Small files and correctness critical? → Use LCS or Myers
  4. Default for most cases? → Use Myers or Histogram
  5. Unsure? → Start with Histogram (Git's recommended choice)

Performance Characteristics Comparison

AlgorithmSpeedOptimalBest For
LCSSlowestYesSmall files, guaranteed correctness
MyersModerateOftenGeneral purpose, version control
PatienceModerateNoCode readability
HistogramFastNoLarge files, balanced approach

Real-World Algorithm Behavior

Example: Moved Code Block

Consider code that moves from one location to another:

// Original
function alpha() { }
function beta() { }
function gamma() { }

// Modified
function gamma() { }
function alpha() { }
function beta() { }

Myers result: Shows all three functions as modified (less intuitive) Patience/Histogram result: Shows gamma moved up, others unchanged (more intuitive)

This is why patience and histogram algorithms are preferred for code.

Configuring Your Diff Tool

Command-Line Configuration

Most tools allow algorithm selection:

# Git with histogram (recommended)
git diff --histogram

# Diff command with options
diff -u file1 file2

# Meld visual diff tool (uses advanced algorithms)
meld file1 file2

GUI Tool Selection

Visual diff tools often handle algorithm selection automatically:

  • Modern tools default to Histogram or Patience
  • Some allow switching algorithms in preferences
  • Better tools adapt algorithm based on file type

Whitespace and Diff Algorithms

All algorithms must handle whitespace considerations:

  • Ignore all whitespace: -w flag
  • Ignore change of whitespace: -b flag
  • Ignore blank lines: -B flag
  • Show all whitespace: Default

Whitespace handling is orthogonal to algorithm choice.

Testing Different Algorithms

For critical comparisons, test multiple algorithms:

# Compare results with different algorithms
git diff --diff-algorithm=myers file.js
git diff --diff-algorithm=patience file.js
git diff --diff-algorithm=histogram file.js

Prefer to see it rather than run it? Paste two versions of a file below and compare them instantly in the browser — no install, nothing leaves your machine.

Loading interactive tool...

When results differ significantly, investigate which makes the most sense for your context.

Conclusion

Different diff algorithms produce different results with different performance characteristics. While users typically don't select algorithms explicitly, understanding the options helps you:

  • Configure Git optimally for your workflows
  • Understand why different diff tools show slightly different results
  • Make informed choices when results seem unexpected
  • Optimize performance for your specific use cases

For most modern users, the default Myers algorithm or Git's Histogram variant serves well. For code-specific use cases, Patience or Histogram algorithms often produce more intuitive results. Understanding these options empowers you to make informed decisions about your diff tool configuration and interpret results accurately.

The key takeaway: there's no single "best" algorithm for all scenarios. Choose based on your specific needs: guaranteed optimality, speed, code readability, or a balanced combination.

Frequently Asked Questions

What diff algorithms does Git support?

Git supports four diff algorithms selectable with git diff --diff-algorithm= or the diff.algorithm config key: myers (the default), minimal (Myers tuned to produce the smallest possible diff), patience, and histogram. Myers and minimal optimize for the fewest changed lines; patience and histogram optimize for readable, human-sensible diffs by anchoring on unique lines first.

Which diff algorithm should I use?

For everyday code review, set histogram — it produces the cleanest diffs on reordered or refactored code and is as fast as Myers on typical files. Use the default myers when you need maximum compatibility or don't care about output shape. Use minimal only when the smallest possible diff matters more than speed. Patience is a good fallback if a specific diff looks scrambled under Myers, though histogram usually beats it.

What is the difference between patience and histogram diff?

Both anchor the diff on lines that appear exactly once (unique lines) so moved and reordered blocks stay intact instead of being scrambled. Histogram is a refinement of patience that also weighs how frequently each line occurs, letting it pick better anchors faster. In practice histogram runs faster than patience and usually produces equal or better output, which is why it's the recommended non-default choice.

Is histogram or Myers better for Git?

Histogram is generally better for reading code because it keeps moved functions and reordered blocks together, while Myers can show a whole reordered region as deleted-and-re-added. Myers remains Git's default for backward compatibility and because it guarantees a minimal edit count. Neither changes what Git commits — the algorithm only affects how the diff is displayed and how patches are shaped.

How do I change the diff algorithm in Git permanently?

Run git config --global diff.algorithm histogram to set it for all repositories, or drop --global to set it per-repo. You can still override per command with git diff --diff-algorithm=patience. The setting also influences git show, git log -p, and merge base comparisons.

Does the diff algorithm change what Git commits or merges?

No. The diff algorithm only affects how differences are computed for display and for generating patch text. The committed content, blob hashes, and history are identical regardless of algorithm. It can influence merge results indirectly (git's merge uses diff internally), but for normal add/commit workflows the choice is purely cosmetic and about readability.

What is the Myers diff algorithm?

The Myers algorithm, published by Eugene Myers in 1986, finds the shortest edit script — the minimum number of line insertions and deletions needed to turn one file into another. It runs in O(ND) time where N is the file length and D is the number of differences, making it fast when changes are small. It's the default in Git, most version-control systems, and the standard diff command.

Why do two diff tools show different results for the same files?

Because they use different algorithms or heuristics. All correct diff algorithms produce a valid set of changes, but there are usually many valid ways to describe the same edit. Myers minimizes edit count; patience and histogram optimize for readability by anchoring on unique lines. Whitespace and end-of-line handling settings add further variation on top of the algorithm choice.

diff algorithmscode comparisonalgorithm selectionperformance optimizationdevelopment tools