Skip to content

Commit 8ee9fb4

Browse files
committed
Optimize RegionMap's MarshalJSON().
- Pregrow the buffer. - Stop calling the encoder for the keys, and insert them as-is. We know all possible keys and can assume that they're safe. This reduces the number of allocations made in FormatHandler by 40%.
1 parent 221f038 commit 8ee9fb4

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

address.go

+8-5
Original file line numberDiff line numberDiff line change
@@ -166,17 +166,20 @@ func (r RegionMap) Len() int {
166166
}
167167

168168
func (r RegionMap) MarshalJSON() ([]byte, error) {
169+
if r.Len() == 0 {
170+
return []byte("{}"), nil
171+
}
169172
buf := &bytes.Buffer{}
170-
encoder := json.NewEncoder(buf)
173+
buf.Grow(r.Len() * 30)
171174
buf.WriteByte('{')
175+
encoder := json.NewEncoder(buf)
172176
for i, key := range r.keys {
173177
if i > 0 {
174178
buf.WriteByte(',')
175179
}
176-
if err := encoder.Encode(key); err != nil {
177-
return nil, err
178-
}
179-
buf.WriteByte(':')
180+
// The key is assumed to be safe and need no escaping.
181+
// Not calling encoder.Encode on the key saves many allocations.
182+
buf.WriteString(`"` + key + `":`)
180183
if err := encoder.Encode(r.values[key]); err != nil {
181184
return nil, err
182185
}

0 commit comments

Comments
 (0)