1
0
mirror of https://github.com/golang/go synced 2024-11-12 03:50:21 -07:00

encoding/csv: Optimize Write by giving fieldNeedsQuotes a fast path for when Comma is ASCII

name     old time/op  new time/op  delta
Write-4  2.37µs ±20%  1.90µs ±19%  -19.54%  (p=0.015 n=6+6)
This commit is contained in:
Alex Gaynor 2019-09-24 16:19:23 -04:00 committed by Alex Gaynor
parent c2e0f01598
commit e7d8b0bd69
2 changed files with 32 additions and 1 deletions

View File

@ -158,10 +158,24 @@ func (w *Writer) fieldNeedsQuotes(field string) bool {
if field == "" { if field == "" {
return false return false
} }
if field == `\.` || strings.ContainsRune(field, w.Comma) || strings.ContainsAny(field, "\"\r\n") {
if field == `\.` {
return true return true
} }
if w.Comma < utf8.RuneSelf {
for i := 0; i < len(field); i++ {
c := field[i]
if c == '\n' || c == '\r' || c == '"' || c == byte(w.Comma) {
return true
}
}
} else {
if strings.ContainsRune(field, w.Comma) || strings.ContainsAny(field, "\"\r\n") {
return true
}
}
r1, _ := utf8.DecodeRuneInString(field) r1, _ := utf8.DecodeRuneInString(field)
return unicode.IsSpace(r1) return unicode.IsSpace(r1)
} }

View File

@ -93,3 +93,20 @@ func TestError(t *testing.T) {
t.Error("Error should not be nil") t.Error("Error should not be nil")
} }
} }
var benchmarkWriteData = [][]string{
{"abc", "def", "12356", "1234567890987654311234432141542132"},
{"abc", "def", "12356", "1234567890987654311234432141542132"},
{"abc", "def", "12356", "1234567890987654311234432141542132"},
}
func BenchmarkWrite(b *testing.B) {
for i := 0; i < b.N; i++ {
w := NewWriter(&bytes.Buffer{})
err := w.WriteAll(benchmarkWriteData)
if err != nil {
b.Fatal(err)
}
w.Flush()
}
}