mirror of
https://blitiri.com.ar/repos/chasquid
synced 2025-12-18 14:47:03 +00:00
normalize: Improve ToCRLF/StringToCRLF performance
The ToCRLF/StringToCRLF functions are not very performance critical, but
we call it for each mail, and the current implementation is very
inefficient (mainly because it goes one byte at a time).
This patch replaces it with a better implementation that goes line by line.
The new implementation of ToCRLF is ~40% faster, and StringToCRLF is ~60%
faster.
```
$ benchstat old.txt new.txt
goos: linux
goarch: amd64
pkg: blitiri.com.ar/go/chasquid/internal/normalize
cpu: 13th Gen Intel(R) Core(TM) i9-13900T
│ old.txt │ new.txt │
│ sec/op │ sec/op vs base │
ToCRLF-32 162.96µ ± 6% 95.42µ ± 12% -41.44% (p=0.000 n=10)
StringToCRLF-32 190.70µ ± 14% 76.51µ ± 6% -59.88% (p=0.000 n=10)
geomean 176.3µ 85.44µ -51.53%
```
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
package normalize
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUser(t *testing.T) {
|
||||
valid := []struct{ user, norm string }{
|
||||
@@ -134,8 +138,19 @@ func TestToCRLF(t *testing.T) {
|
||||
in, out string
|
||||
}{
|
||||
{"", ""},
|
||||
{"a", "a"},
|
||||
|
||||
// Does not end in newline.
|
||||
{"a\n", "a\r\n"},
|
||||
{"a\nb", "a\r\nb"},
|
||||
{"a\r\nb", "a\r\nb"},
|
||||
|
||||
// Ends in newline.
|
||||
{"a\nb\n", "a\r\nb\r\n"},
|
||||
{"a\r\nb\n", "a\r\nb\r\n"},
|
||||
{"a\r\nb\r\n", "a\r\nb\r\n"},
|
||||
{"a\r\nb\n\n", "a\r\nb\r\n\r\n"},
|
||||
{"a\r\nb\r\n\r\n", "a\r\nb\r\n\r\n"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := string(ToCRLF([]byte(c.in)))
|
||||
@@ -173,3 +188,31 @@ func FuzzDomainToUnicode(f *testing.F) {
|
||||
DomainToUnicode(addr)
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkToCRLF(b *testing.B) {
|
||||
// Generate a 1000-line message.
|
||||
bb := bytes.Buffer{}
|
||||
for i := 0; i < 1000; i++ {
|
||||
bb.WriteString("this is a very pretty line 🐅\n")
|
||||
}
|
||||
buf := bb.Bytes()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ToCRLF(buf)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStringToCRLF(b *testing.B) {
|
||||
// Generate a 1000-line message.
|
||||
sb := strings.Builder{}
|
||||
for i := 0; i < 1000; i++ {
|
||||
sb.WriteString("this is a very pretty line 🐅\n")
|
||||
}
|
||||
s := sb.String()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
StringToCRLF(s)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user