fiff

A text diff that reads only as far as it must.

What it is

FIFF compares two text files and lists where they differ. I wrote it in C# for Code Project's Code Lean and Mean competition, where the goal was a diff that is fast and small on large files with few changes. Its article survives in the Wayback Machine's copy of 10 January 2012.

This is its JavaScript port, running in your browser. It fixes four bugs the original has, and keeps its one deliberate trade-off.

How it works

  1. Read both files a chunk at a time. While the chunks match, there is nothing to do.
  2. At the first chunk that differs, read it again as tokens. A token ends at the delimiter you choose, a space or a line end, and always at a line end.
  3. Walk both token lists side by side. When the two current tokens differ, look for each one among the other side's tokens read so far. The nearer match ends the difference.
  4. Report what came before the match on each side, ignoring case, then go back to reading chunks.

Unordered mode reads every token and asks only whether the other file has it, anywhere. Each token cancels one copy on the other side, so the same words in another order are no difference, and a repeated word still counts.

Try it

Options

File 1


          

File 2


          
Each difference, as FIFF reports it: where it starts in each file, in bytes, and its text
#File 1 atFile 1 textFile 2 atFile 2 text

What it trades

A difference ends at the first token both sides share. That is what keeps FIFF quick when changes are few: it never looks past the end of a difference. But a line that repeats through a file, like <TR vAlign=top>, can end a difference too early and split one change into two.

The smallest diff, by longest common subsequence, never does that, and costs time in the product of the two lengths. Pick The competition test above: FIFF's differences hold 25 lines where the smallest diff holds 19. The original's article names this case itself.

The code

src/fiff.js is the port, with no dependencies. The demo above judges each answer with the checks the tests use: that it lists as many differences as it counts, that each sits in its file where it says, and, ordered, that taking them out leaves the same text on both sides, or, unordered, that each side holds exactly the tokens the other lacks. The README traces each of the original's bugs to its line and says how the port fixes it.