From ce2ea4448dd632c27f7092726ef189cf22fb11d4 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Thu, 26 Nov 2026 17:02:58 +0900 Subject: [PATCH] diffview: diff a large file three times faster A diff of a file of 100,000 lines took 66 ms before it drew a line. Most of the time went to the regular expression that scopesOf ran on each line to find the declarations, and to go-udiff's splitLines, which decodes every rune to find the line ends. isDeclaration now reads the words at the start of a line by hand, and matches the same lines as the regular expression, which a test keeps as the reference. The cheap check for a word at column 0 comes first, so most top-level lines skip it. Edits replaces udiff.Lines, in the way of @pierre/patches: it finds the line ends with strings.IndexByte, diffs integer ids of the lines, and slices the new text instead of copying it. It returns the same edits as udiff.Lines. BenchmarkDiffHunks, 100,000 lines, Apple M4: one line changed in 2,000: 65.9 ms, 40.9 MB -> 21.3 ms, 24.2 MB 2,000 lines inserted: 40.2 ms, 41.6 MB -> 15.3 ms, 24.8 MB --- diff/diff.go | 2 +- internal/diffview/diffview.go | 51 +++++++++++++++++++++- internal/diffview/edits_test.go | 76 +++++++++++++++++++++++++++++++++ internal/diffview/scope.go | 65 +++++++++++++++++++++++++--- internal/diffview/scope_test.go | 25 +++++++++++ 5 files changed, 211 insertions(+), 8 deletions(-) create mode 100644 internal/diffview/edits_test.go diff --git a/diff/diff.go b/diff/diff.go index d6210fa..83d62bb 100644 --- a/diff/diff.go +++ b/diff/diff.go @@ -169,7 +169,7 @@ func (d *Diff) SideAt(x int) (s Side, onNumber bool) { func Count(old, new string) (added, deleted int) { old = strings.ReplaceAll(old, "\r\n", "\n") new = strings.ReplaceAll(new, "\r\n", "\n") - u, err := udiff.ToUnifiedDiff("", "", old, udiff.Lines(old, new), 0) + u, err := udiff.ToUnifiedDiff("", "", old, diffview.Edits(old, new), 0) if err != nil { return 0, 0 } diff --git a/internal/diffview/diffview.go b/internal/diffview/diffview.go index c09b09e..328756e 100644 --- a/internal/diffview/diffview.go +++ b/internal/diffview/diffview.go @@ -12,6 +12,7 @@ import ( "charm.land/lipgloss/v2" "github.com/aymanbagabas/go-udiff" + "github.com/aymanbagabas/go-udiff/lcs" "github.com/charmbracelet/x/ansi" ) @@ -123,7 +124,7 @@ func Render(path, before, after string, o Options) ([]string, []Row, Geometry) { // diffHunks computes the hunks of the diff, with the tabs of the lines // replaced after the diff, so that a change from a tab to spaces shows. func diffHunks(before, after string, tabWidth, context int) []hunk { - u, err := udiff.ToUnifiedDiff("", "", before, udiff.Lines(before, after), context) + u, err := udiff.ToUnifiedDiff("", "", before, Edits(before, after), context) if err != nil { return nil } @@ -168,6 +169,54 @@ func diffHunks(before, after string, tabWidth, context int) []hunk { return hunks } +// Edits returns the line edits that change before into after. They are +// the same as the edits of udiff.Lines, but Edits takes less time on a +// large file, in the way of @pierre/patches: it finds the line ends with +// strings.IndexByte instead of decoding each rune, it diffs integer ids of +// the lines instead of the lines, and the new text of an edit is a slice +// of after instead of a copy. +func Edits(before, after string) []udiff.Edit { + ids := make(map[string]rune) + a, aOffsets := lineIDs(before, ids) + b, bOffsets := lineIDs(after, ids) + // The lcs package compares only for equality, and two lines have the + // same id only if they are equal, so the runes give the same diff as + // the lines. + diffs := lcs.DiffRunes(a, b) + edits := make([]udiff.Edit, len(diffs)) + for i, d := range diffs { + edits[i] = udiff.Edit{ + Start: aOffsets[d.Start], + End: aOffsets[d.End], + New: after[bOffsets[d.ReplStart]:bOffsets[d.ReplEnd]], + } + } + return edits +} + +// lineIDs splits s into lines, each with its LF, and returns the id of +// each line from ids, which it adds new lines to. The offsets are the +// start of each line and then the end of s. +func lineIDs(s string, ids map[string]rune) (lines []rune, offsets []int) { + n := strings.Count(s, "\n") + 1 + lines, offsets = make([]rune, 0, n), make([]int, 1, n+1) + for start := 0; start < len(s); { + end := len(s) + if i := strings.IndexByte(s[start:], '\n'); i >= 0 { + end = start + i + 1 + } + id, ok := ids[s[start:end]] + if !ok { + id = rune(len(ids)) + ids[s[start:end]] = id + } + lines = append(lines, id) + offsets = append(offsets, end) + start = end + } + return lines, offsets +} + // pairs puts the lines of a hunk side by side. An equal line is on both // sides. In each run of changed lines, the n-th deleted line is beside the // n-th inserted line. A nil side has no line. diff --git a/internal/diffview/edits_test.go b/internal/diffview/edits_test.go new file mode 100644 index 0000000..4397b2f --- /dev/null +++ b/internal/diffview/edits_test.go @@ -0,0 +1,76 @@ +package diffview + +import ( + "fmt" + "math/rand/v2" + "reflect" + "strings" + "testing" + + "github.com/aymanbagabas/go-udiff" +) + +// TestEditsMatchUdiff checks that Edits gives the same edits as +// udiff.Lines, which it replaces. The lines come from a few values, so +// that many of them repeat. +func TestEditsMatchUdiff(t *testing.T) { + values := []string{"", "a", "b", "}", "\tx := 1", "\r", "\xe2", "é"} + text := func(r *rand.Rand) string { + var b strings.Builder + for range r.IntN(30) { + b.WriteString(values[r.IntN(len(values))] + "\n") + } + if r.IntN(2) == 0 { // a last line without LF + b.WriteString(values[r.IntN(len(values))]) + } + return b.String() + } + r := rand.New(rand.NewPCG(1, 2)) + for range 10_000 { + before, after := text(r), text(r) + if got, want := Edits(before, after), udiff.Lines(before, after); !reflect.DeepEqual(got, want) { + t.Fatalf("Edits(%q, %q)\n got %v\nwant %v", before, after, got, want) + } + } +} + +// BenchmarkDiffHunks diffs two versions of a file of 100,000 lines, as +// Render does before it draws them: +// +// go test ./internal/diffview -run '^$' -bench DiffHunks -count 10 +func BenchmarkDiffHunks(b *testing.B) { + const n = 100_000 + lines := make([]string, n) + for i := range lines { + switch i % 10 { + case 0: + lines[i] = "}" + case 1: + lines[i] = "" + default: + lines[i] = fmt.Sprintf("\tx%d := compute(%q, %d) // a line of a large file", i, strings.Repeat("a", i%40), i) + } + } + before := strings.Join(lines, "\n") + "\n" + + // Edits changes one line in every 2,000. + edited := append([]string(nil), lines...) + for i := 1000; i < n; i += 2000 { + edited[i] += " // changed" + } + // Insert adds a block of 2,000 lines in the middle. + inserted := append(append(append([]string(nil), lines[:n/2]...), lines[:2000]...), lines[n/2:]...) + + for _, c := range []struct{ name, after string }{ + {"edits", strings.Join(edited, "\n") + "\n"}, + {"insert", strings.Join(inserted, "\n") + "\n"}, + } { + b.Run(c.name, func(b *testing.B) { + b.SetBytes(int64(len(before) + len(c.after))) + b.ReportAllocs() + for b.Loop() { + diffHunks(before, c.after, 8, 3) + } + }) + } +} diff --git a/internal/diffview/scope.go b/internal/diffview/scope.go index 277aa8f..3e35b9a 100644 --- a/internal/diffview/scope.go +++ b/internal/diffview/scope.go @@ -1,13 +1,66 @@ package diffview import ( - "regexp" "strings" ) -// declaration matches a line that declares a function, a type, or a -// module in most languages, after optional modifiers such as "pub". -var declaration = regexp.MustCompile(`^\s*(?:(?:export|pub(?:\([a-z]+\))?|public|private|protected|internal|static|async|abstract|final|sealed|open|override|default|unsafe|inline|virtual|extern|data|const)\s+)*(?:def|class|func|fn|fun|function|struct|enum|union|trait|impl|interface|type|module|mod|namespace|object|record|protocol|extension|actor|macro|sub|proc)\b`) +// The words that start a declaration of a function, a type, or a module in +// most languages, and the modifiers that can come before them. +var ( + keywords = wordSet("def class func fn fun function struct enum union trait impl interface type module mod namespace object record protocol extension actor macro sub proc") + modifiers = wordSet("export pub public private protected internal static async abstract final sealed open override default unsafe inline virtual extern data const") +) + +func wordSet(s string) map[string]bool { + set := map[string]bool{} + for _, w := range strings.Fields(s) { + set[w] = true + } + return set +} + +// space is the set of \s in a regular expression. +const space = " \t\n\f\r" + +// isDeclaration reports whether l declares a function, a type, or a +// module: after indent and modifiers such as "pub" or "pub(crate)", the +// first word is a keyword such as "func". It matches the same lines as +// the regular expression +// +// ^\s*(?:(?:modifier|pub\([a-z]+\))\s+)*keyword\b +// +// but scopesOf calls it on each line of a file, and the regular expression +// took most of the time of a large diff. +func isDeclaration(l string) bool { + s := strings.TrimLeft(l, space) + for { + n := 0 + for n < len(s) && isWordByte(s[n]) { + n++ + } + w, rest := s[:n], s[n:] + if keywords[w] { + return true + } + if !modifiers[w] { + return false + } + if w == "pub" && strings.HasPrefix(rest, "(") { + if i := strings.IndexByte(rest, ')'); i > 1 && strings.Trim(rest[1:i], "abcdefghijklmnopqrstuvwxyz") == "" { + rest = rest[i+1:] + } + } + s = strings.TrimLeft(rest, space) + if len(s) == len(rest) { // a modifier needs space after it + return false + } + } +} + +// isWordByte reports whether b is in \w, the bytes of a word. +func isWordByte(b byte) bool { + return b == '_' || '0' <= b && b <= '9' || 'a' <= b|0x20 && b|0x20 <= 'z' +} // scopesOf returns the scope of each line in firsts (0-based, ascending): // the line that encloses it, as "def foo(" or "func (v *View) text() string {", @@ -33,8 +86,8 @@ func scopesOf(lines []string, firsts []int) []string { } d := indent(l) c := l[d] - if declaration.MatchString(l) || - d == 0 && (c == '_' || c == '$' || 'a' <= c|0x20 && c|0x20 <= 'z') { + if d == 0 && (c == '_' || c == '$' || 'a' <= c|0x20 && c|0x20 <= 'z') || + isDeclaration(l) { for len(stack) > 0 && stack[len(stack)-1].indent >= d { stack = stack[:len(stack)-1] } diff --git a/internal/diffview/scope_test.go b/internal/diffview/scope_test.go index 438fa93..3962835 100644 --- a/internal/diffview/scope_test.go +++ b/internal/diffview/scope_test.go @@ -1,6 +1,8 @@ package diffview import ( + "math/rand/v2" + "regexp" "strings" "testing" ) @@ -31,3 +33,26 @@ func TestScopesOfMany(t *testing.T) { t.Errorf("got %q, want %q", got, want) } } + +// TestIsDeclarationMatchesRegexp checks that isDeclaration matches the +// same lines as the regular expression it replaces. The lines join +// random pieces of declarations, words, and spaces. +func TestIsDeclarationMatchesRegexp(t *testing.T) { + declaration := regexp.MustCompile(`^\s*(?:(?:export|pub(?:\([a-z]+\))?|public|private|protected|internal|static|async|abstract|final|sealed|open|override|default|unsafe|inline|virtual|extern|data|const)\s+)*(?:def|class|func|fn|fun|function|struct|enum|union|trait|impl|interface|type|module|mod|namespace|object|record|protocol|extension|actor|macro|sub|proc)\b`) + pieces := []string{ + "func", "fn", "def", "class", "define", "Func", "fn_", "func2", "funcé", + "pub", "pub(crate)", "pub(Crate)", "pub()", "pub(", ")", "public", "static", "async", + " ", " ", "\t", "\v", "\f", "\r", "x", "_", "é", "(", ":", "{", "$", + } + r := rand.New(rand.NewPCG(3, 4)) + for range 200_000 { + var b strings.Builder + for range r.IntN(6) { + b.WriteString(pieces[r.IntN(len(pieces))]) + } + l := b.String() + if got, want := isDeclaration(l), declaration.MatchString(l); got != want { + t.Fatalf("isDeclaration(%q) = %v, want %v", l, got, want) + } + } +}