Skip to content

Commit f78a839

Browse files
author
Patrick Mézard
committed
Merge pull request #1 from rdwilliamson/master
difflib: optimize SplitLines
2 parents 8fee7c0 + b65e32b commit f78a839

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

difflib/difflib.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -752,9 +752,7 @@ func GetContextDiffString(diff ContextDiff) (string, error) {
752752
// Split a string on "\n" while preserving them. The output can be used
753753
// as input for UnifiedDiff and ContextDiff structures.
754754
func SplitLines(s string) []string {
755-
lines := []string{}
756-
for _, line := range strings.Split(s, "\n") {
757-
lines = append(lines, line+"\n")
758-
}
755+
lines := strings.SplitAfter(s, "\n")
756+
lines[len(lines)-1] += "\n"
759757
return lines
760758
}

difflib/difflib_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,3 +317,36 @@ func TestOutputFormatNoTrailingTabOnEmptyFiledate(t *testing.T) {
317317
assertEqual(t, err, nil)
318318
assertEqual(t, SplitLines(cd)[:2], []string{"*** Original\n", "--- Current\n"})
319319
}
320+
321+
func TestSplitLines(t *testing.T) {
322+
allTests := []struct {
323+
input string
324+
want []string
325+
}{
326+
{"foo", []string{"foo\n"}},
327+
{"foo\nbar", []string{"foo\n", "bar\n"}},
328+
{"foo\nbar\n", []string{"foo\n", "bar\n", "\n"}},
329+
}
330+
for _, test := range allTests {
331+
assertEqual(t, SplitLines(test.input), test.want)
332+
}
333+
}
334+
335+
func benchmarkSplitLines(b *testing.B, count int) {
336+
str := strings.Repeat("foo\n", count)
337+
338+
b.ResetTimer()
339+
340+
n := 0
341+
for i := 0; i < b.N; i++ {
342+
n += len(SplitLines(str))
343+
}
344+
}
345+
346+
func BenchmarkSplitLines100(b *testing.B) {
347+
benchmarkSplitLines(b, 100)
348+
}
349+
350+
func BenchmarkSplitLines10000(b *testing.B) {
351+
benchmarkSplitLines(b, 10000)
352+
}

0 commit comments

Comments
 (0)