fix: improve json marshal performance, reduce necessary allocations

This commit is contained in:
yusing
2025-04-17 06:44:07 +08:00
parent af8bf197c9
commit a35ac33bd5
5 changed files with 84 additions and 87 deletions

View File

@@ -21,9 +21,7 @@ var (
//
// It's like json.Marshal, but with some differences:
//
// - It's ~4-5x faster in most cases.
//
// - It also supports custom Marshaler interface (MarshalJSONTo(buf []byte) []byte)
// - It supports custom Marshaler interface (MarshalJSONTo(buf []byte) []byte)
// to allow further optimizations.
//
// - It leverages the strutils library.
@@ -36,7 +34,7 @@ var (
//
// `use_marshaler` to force using the custom marshaler for primitive types declaration (e.g. `type Status int`).
//
// - It correct the behavior of *url.URL and time.Duration.
// - It corrects the behavior of *url.URL and time.Duration.
//
// - It does not support maps other than string-keyed maps.
func Marshal(v any) ([]byte, error) {
@@ -49,7 +47,7 @@ func MarshalTo(v any, buf []byte) []byte {
return appendMarshal(reflect.ValueOf(v), buf)
}
const bufSize = 1024
const bufSize = 8192
var bytesPool = sync.Pool{
New: func() any {