Video in progress

You're writing a service that shows the difference between versions of a config or a document. Which diff algorithm do you choose, and what do you watch for on large files?

By lines, Myers' algorithm is the standard choice: it finds the minimal edit list in O((n+m)·D), where D is the size of the difference, so it's very fast on similar files. For structured data (JSON, YAML), a diff over the tree is more correct than over text. For large and very different files, you need a time limit and a heuristic.

📖 Answer

Diff is another form of the LCS problem: everything outside the common subsequence is either added or deleted. The classic DP takes O(n·m) time and memory, which for two 100,000-line files is 10¹⁰ cells, not feasible.

The Myers idea: search for a path by the number of edits D, keeping for each D the "furthest reach" along each diagonal. If the files are nearly identical, D is small and the algorithm is nearly linear. This is Git's default. In Java, the java-diff-utils library gives you Myers ready-made.

In practice these are the decisions you make.

By which unit? Lines for code and configuration. Words or characters for prose, and for showing changes inside a line (first a line diff, then a word diff inside the pairs of changed lines).

Myers gives a minimal diff, but it isn't always readable: } lines get paired wrongly and it looks as if a function was moved. Patience diff anchors only on unique lines, giving a result that is easier for humans to follow. In Git it's --diff-algorithm=patience or its faster extension, histogram.

Structured data. In YAML, if the order of keys changes, a line diff shows the whole file as changed when nothing changed in meaning. I parse the config and compare the trees by path: spring.datasource.url: old → new. For lists, you have to match elements by identifier, not by index, and that's a separate design decision. For JSON, the RFC 6902 JSON Patch format gives the result in a standard form.

You need protection too: with two completely different 50 MB files, D is large and Myers approaches quadratic. A limit on input size, a time budget for the computation, and, beyond that, a simplified answer of "the file was fully replaced". Git has heuristics like this as well.

For storage: keeping every version in full is simple and reliable; storing deltas saves space, but restoring an old version means applying a chain. A full snapshot every N versions is the usual compromise.

For the user, what matters most is often not the algorithm but removing noise: a setting that hides irrelevant differences such as whitespace, key order and timestamps.