From 2828fa21c0ffd2a32a108b37c0417b01abc42929 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Thu, 26 Jan 2023 21:02:56 -0700 Subject: Avoid doing type switching in inner functions The CPU profiler tells me that the encoder is spending a lot of time on type switches. --- encode.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'encode.go') diff --git a/encode.go b/encode.go index e9c7ac6..c5a29b3 100644 --- a/encode.go +++ b/encode.go @@ -18,6 +18,8 @@ import ( "strconv" "strings" "unsafe" + + "git.lukeshu.com/go/lowmemjson/internal" ) // Encodable is the interface implemented by types that can encode @@ -34,14 +36,14 @@ type encodeError struct { Err error } -func encodeWriteByte(w io.Writer, b byte) { - if err := writeByte(w, b); err != nil { +func encodeWriteByte(w io.ByteWriter, b byte) { + if err := w.WriteByte(b); err != nil { panic(encodeError{err}) } } -func encodeWriteString(w io.Writer, str string) { - if _, err := io.WriteString(w, str); err != nil { +func encodeWriteString(w io.StringWriter, str string) { + if _, err := w.WriteString(str); err != nil { panic(encodeError{err}) } } @@ -115,7 +117,7 @@ var ( const startDetectingCyclesAfter = 1000 -func encode(w io.Writer, val reflect.Value, escaper BackslashEscaper, quote bool, cycleDepth uint, cycleSeen map[any]struct{}) { +func encode(w internal.AllWriter, val reflect.Value, escaper BackslashEscaper, quote bool, cycleDepth uint, cycleSeen map[any]struct{}) { if !val.IsValid() { encodeWriteString(w, "null") return @@ -436,7 +438,7 @@ func encode(w io.Writer, val reflect.Value, escaper BackslashEscaper, quote bool } } -func encodeArray(w io.Writer, val reflect.Value, escaper BackslashEscaper, cycleDepth uint, cycleSeen map[any]struct{}) { +func encodeArray(w internal.AllWriter, val reflect.Value, escaper BackslashEscaper, cycleDepth uint, cycleSeen map[any]struct{}) { encodeWriteByte(w, '[') n := val.Len() for i := 0; i < n; i++ { -- cgit v1.2.3