summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@lukeshu.com>2023-02-15 18:58:51 -0700
committerLuke Shumaker <lukeshu@lukeshu.com>2023-02-16 22:56:05 -0700
commit30e0ee4ced0be18b4df91674fd6f073793b61fe9 (patch)
tree378e4acbf0f3b1cac9258aa7de3b9c4f62d6259f
parenta0e44530509d3b342b8011ac4467d957350f5ffa (diff)
encode: Avoid allocations when formatting integers
-rw-r--r--encode.go13
1 files changed, 11 insertions, 2 deletions
diff --git a/encode.go b/encode.go
index 2e10134..38a2e93 100644
--- a/encode.go
+++ b/encode.go
@@ -228,7 +228,12 @@ func encode(w *ReEncoder, val reflect.Value, escaper BackslashEscaper, quote boo
return err
}
}
- if _, err := w.WriteString(strconv.FormatInt(val.Int(), 10)); err != nil {
+ // MaxInt64 = 9223372036854775807
+ // MinInt64 = -9223372036854775808
+ // 0 1 2
+ // 12345678901234567890
+ var buf [20]byte
+ if _, err := w.Write(strconv.AppendInt(buf[:0], val.Int(), 10)); err != nil {
return err
}
if quote {
@@ -242,7 +247,11 @@ func encode(w *ReEncoder, val reflect.Value, escaper BackslashEscaper, quote boo
return err
}
}
- if _, err := w.WriteString(strconv.FormatUint(val.Uint(), 10)); err != nil {
+ // MaxUint64 = 18446744073709551615
+ // 0 1 2
+ // 12345678901234567890
+ var buf [20]byte
+ if _, err := w.Write(strconv.AppendUint(buf[:0], val.Uint(), 10)); err != nil {
return err
}
if quote {