1
0
mirror of https://github.com/golang/go synced 2024-11-18 15:54:42 -07:00

encoding/pem: eliminate allocations for newlines during encoding

benchmark           old MB/s     new MB/s     speedup
BenchmarkEncode     243.20       279.89       1.15x

benchmark           old allocs     new allocs     delta
BenchmarkEncode     1370           4              -99.71%

Change-Id: I3920bcc04b6dd89efa5da89db5594d4434426d74
Reviewed-on: https://go-review.googlesource.com/1924
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
Ben Burkert 2014-12-21 13:31:23 -08:00 committed by Brad Fitzpatrick
parent f34964ed34
commit e4c2229e4c
2 changed files with 24 additions and 3 deletions

View File

@ -171,6 +171,8 @@ type lineBreaker struct {
out io.Writer
}
var nl = []byte{'\n'}
func (l *lineBreaker) Write(b []byte) (n int, err error) {
if l.used+len(b) < pemLineLength {
copy(l.line[l.used:], b)
@ -190,7 +192,7 @@ func (l *lineBreaker) Write(b []byte) (n int, err error) {
return
}
n, err = l.out.Write([]byte{'\n'})
n, err = l.out.Write(nl)
if err != nil {
return
}
@ -204,7 +206,7 @@ func (l *lineBreaker) Close() (err error) {
if err != nil {
return
}
_, err = l.out.Write([]byte{'\n'})
_, err = l.out.Write(nl)
}
return
@ -248,7 +250,7 @@ func Encode(out io.Writer, b *Block) error {
return err
}
}
if _, err := out.Write([]byte{'\n'}); err != nil {
if _, err := out.Write(nl); err != nil {
return err
}
}

View File

@ -6,6 +6,7 @@ package pem
import (
"bytes"
"io/ioutil"
"reflect"
"testing"
)
@ -116,6 +117,24 @@ func TestLineBreaker(t *testing.T) {
}
}
func BenchmarkEncode(b *testing.B) {
data := &Block{Bytes: make([]byte, 65536)}
b.SetBytes(int64(len(data.Bytes)))
for i := 0; i < b.N; i++ {
Encode(ioutil.Discard, data)
}
}
func BenchmarkDecode(b *testing.B) {
block := &Block{Bytes: make([]byte, 65536)}
data := EncodeToMemory(block)
b.SetBytes(int64(len(data)))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Decode(data)
}
}
var pemData = `verify return:0
-----BEGIN CERTIFICATE-----
sdlfkjskldfj