Skip to content

Commit

Permalink
Merge pull request #1 from rdwilliamson/master
Browse files Browse the repository at this point in the history
difflib: optimize SplitLines
  • Loading branch information
Patrick Mézard committed May 10, 2015
2 parents 8fee7c0 + b65e32b commit f78a839
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
6 changes: 2 additions & 4 deletions difflib/difflib.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,9 +752,7 @@ func GetContextDiffString(diff ContextDiff) (string, error) {
// Split a string on "\n" while preserving them. The output can be used
// as input for UnifiedDiff and ContextDiff structures.
func SplitLines(s string) []string {
lines := []string{}
for _, line := range strings.Split(s, "\n") {
lines = append(lines, line+"\n")
}
lines := strings.SplitAfter(s, "\n")
lines[len(lines)-1] += "\n"
return lines
}
33 changes: 33 additions & 0 deletions difflib/difflib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,36 @@ func TestOutputFormatNoTrailingTabOnEmptyFiledate(t *testing.T) {
assertEqual(t, err, nil)
assertEqual(t, SplitLines(cd)[:2], []string{"*** Original\n", "--- Current\n"})
}

func TestSplitLines(t *testing.T) {
allTests := []struct {
input string
want []string
}{
{"foo", []string{"foo\n"}},
{"foo\nbar", []string{"foo\n", "bar\n"}},
{"foo\nbar\n", []string{"foo\n", "bar\n", "\n"}},
}
for _, test := range allTests {
assertEqual(t, SplitLines(test.input), test.want)
}
}

func benchmarkSplitLines(b *testing.B, count int) {
str := strings.Repeat("foo\n", count)

b.ResetTimer()

n := 0
for i := 0; i < b.N; i++ {
n += len(SplitLines(str))
}
}

func BenchmarkSplitLines100(b *testing.B) {
benchmarkSplitLines(b, 100)
}

func BenchmarkSplitLines10000(b *testing.B) {
benchmarkSplitLines(b, 10000)
}

0 comments on commit f78a839

Please sign in to comment.