Skip to content

Commit

Permalink
encoding/pem: eliminate allocations for newlines during encoding
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
benburkert authored and bradfitz committed Dec 21, 2014
1 parent f34964e commit e4c2229
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/encoding/pem/pem.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
}
Expand All @@ -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
Expand Down Expand Up @@ -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
}
}
Expand Down
19 changes: 19 additions & 0 deletions src/encoding/pem/pem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package pem

import (
"bytes"
"io/ioutil"
"reflect"
"testing"
)
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit e4c2229

Please sign in to comment.