Skip to content

Commit

Permalink
Cache the most recently used valueEncoder to avoid a hash table lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
ianlopshire committed Jan 13, 2022
1 parent be3e43b commit 5919528
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ type Encoder struct {
lineTerminator []byte

useCodepointIndices bool

lastType reflect.Type
lastValueEncoder valueEncoder
}

// NewEncoder returns a new encoder that writes to w.
Expand Down Expand Up @@ -132,7 +135,15 @@ func (e *Encoder) writeLines(v reflect.Value) error {
}

func (e *Encoder) writeLine(v reflect.Value) (err error) {
b, err := newValueEncoder(v.Type(), e.useCodepointIndices)(v)
t := v.Type()
encoder := e.lastValueEncoder
if e.lastType != t {
e.lastType = t
e.lastValueEncoder = newValueEncoder(t, e.useCodepointIndices)
encoder = e.lastValueEncoder
}

b, err := encoder(v)
if err != nil {
return err
}
Expand Down

0 comments on commit 5919528

Please sign in to comment.