fix: improve json marshal performance, reduce necessary allocations

This commit is contained in:
yusing
2025-04-17 06:10:13 +08:00
parent af8bf197c9
commit e2717c9e44
3 changed files with 66 additions and 64 deletions

View File

@@ -1,7 +1,6 @@
package json
import (
"reflect"
"sync"
"github.com/bytedance/sonic"
@@ -21,9 +20,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,20 +33,20 @@ 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) {
buf := newBytes()
defer putBytes(buf)
return cloneBytes(appendMarshal(reflect.ValueOf(v), buf)), nil
return cloneBytes(appendMarshalAny(v, buf)), nil
}
func MarshalTo(v any, buf []byte) []byte {
return appendMarshal(reflect.ValueOf(v), buf)
return appendMarshalAny(v, buf)
}
const bufSize = 1024
const bufSize = 8192
var bytesPool = sync.Pool{
New: func() any {