Reducing memory allocation events

Former-commit-id: c94e79ba116464504580fc397270ead154063971
This commit is contained in:
Eric Coissac
2024-06-22 22:32:31 +02:00
parent e6b87ecd02
commit 93f9dcb95f
8 changed files with 98 additions and 46 deletions

View File

@ -363,6 +363,16 @@ func AtomicCounter(initial ...int) func() int {
return nextCounter
}
func JsonMarshalByteBuffer(buffer *bytes.Buffer, i interface{}) error {
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(i)
b := buffer.Bytes()
b = bytes.TrimRight(b, "\n")
buffer.Truncate(len(b))
return err
}
// JsonMarshal marshals an interface into JSON format.
//
// JsonMarshal is a UTF-8 friendly marshaler. Go's json.Marshal is not UTF-8
@ -375,10 +385,8 @@ func AtomicCounter(initial ...int) func() int {
// It takes an interface as a parameter and returns a byte slice and an error.
func JsonMarshal(i interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(i)
return bytes.TrimRight(buffer.Bytes(), "\n"), err
err := JsonMarshalByteBuffer(buffer, i)
return buffer.Bytes(), err
}
// IsAMap checks if the given value is a map.