Skip to content

Commit

Permalink
Remove unnecessary defer in Encoder.EncodeKeyval.
Browse files Browse the repository at this point in the history
This change results in a nice speed improvement for a method that is
normally called within a loop.

name            old time/op    new time/op    delta
EncodeKeyval-4    1.74µs ± 1%    1.46µs ± 1%  -16.39%    (p=0.000 n=10+9)
  • Loading branch information
ChrisHines committed May 8, 2016
1 parent 08ab82a commit a5fe813
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ var (
// single space is written before the second and subsequent keys in a record.
// Nothing is written if a non-nil error is returned.
func (enc *Encoder) EncodeKeyval(key, value interface{}) error {
defer enc.scratch.Reset()
enc.scratch.Reset()
if enc.needSep {
if _, err := enc.scratch.Write(space); err != nil {
return err
Expand Down
10 changes: 10 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -187,3 +188,12 @@ type errorMarshaler struct{}
func (errorMarshaler) MarshalText() ([]byte, error) {
return nil, marshalError
}

func BenchmarkEncodeKeyval(b *testing.B) {
b.ReportAllocs()
enc := logfmt.NewEncoder(ioutil.Discard)
for i := 0; i < b.N; i++ {
enc.EncodeKeyval("sk", "10")
enc.EncodeKeyval("some-key", "a rather long string with spaces")
}
}

0 comments on commit a5fe813

Please sign in to comment.