Skip to content

Commit 9846cb5

Browse files
author
Ignacio Van Droogenbroeck
committed
perf(encode): add map[string]string fast path in Encode() type switch
Adds a direct type assertion case for map[string]string in Encode(), bypassing reflect.ValueOf + getEncoder dispatch. Also adds encodeMapStringString method that operates on the concrete type without reflection. Benchmark: MapStringString 192 ns -> 164 ns (-15%)
1 parent 82f46cf commit 9846cb5

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

encode.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,8 @@ func (e *Encoder) Encode(v interface{}) error {
243243
return e.encodeInt64Cond(int64(v))
244244
case time.Time:
245245
return e.EncodeTime(v)
246+
case map[string]string:
247+
return e.encodeMapStringString(v)
246248
case map[string]interface{}:
247249
if e.flags&sortMapKeysFlag != 0 {
248250
return e.EncodeMapSorted(v)

encode_map.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,27 @@ func encodeMapStringInterfaceValue(e *Encoder, v reflect.Value) error {
9393
return e.EncodeMap(m)
9494
}
9595

96+
func (e *Encoder) encodeMapStringString(m map[string]string) error {
97+
if m == nil {
98+
return e.EncodeNil()
99+
}
100+
if err := e.EncodeMapLen(len(m)); err != nil {
101+
return err
102+
}
103+
if e.flags&sortMapKeysFlag != 0 {
104+
return e.encodeSortedMapStringString(m)
105+
}
106+
for mk, mv := range m {
107+
if err := e.EncodeString(mk); err != nil {
108+
return err
109+
}
110+
if err := e.EncodeString(mv); err != nil {
111+
return err
112+
}
113+
}
114+
return nil
115+
}
116+
96117
func (e *Encoder) EncodeMap(m map[string]interface{}) error {
97118
if m == nil {
98119
return e.EncodeNil()

0 commit comments

Comments
 (0)