From e0f64db92c03697d0f2f9206fec98aa15f86849e Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 8 Apr 2020 12:50:19 +0300 Subject: [PATCH] minimize allocations (#1472) * server: minimize allocations on re-register Signed-off-by: Vasiliy Tolstov * server: stop old instance before Init() Signed-off-by: Vasiliy Tolstov * client/grpc: fix allocations in protobuf marshal Signed-off-by: Vasiliy Tolstov * codec/json: fix allocations in protobuf marshal Signed-off-by: Vasiliy Tolstov * remove stop from init Signed-off-by: Vasiliy Tolstov * codec/grpc: expose MaxMessageSize Signed-off-by: Vasiliy Tolstov * codec: use buffer pool Signed-off-by: Vasiliy Tolstov * metadata: minimize reallocations Signed-off-by: Vasiliy Tolstov * util/wrapper: use metadata helper Signed-off-by: Vasiliy Tolstov * registry/cache: move logs to debug level Signed-off-by: Vasiliy Tolstov * server: move logs to debug level Signed-off-by: Vasiliy Tolstov * server: cache service only when Advertise is ip addr Signed-off-by: Vasiliy Tolstov * server: use metadata.Copy Signed-off-by: Vasiliy Tolstov --- codec.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/codec.go b/codec.go index a7ee99f..e5a6730 100644 --- a/codec.go +++ b/codec.go @@ -11,6 +11,7 @@ import ( "github.com/golang/protobuf/proto" "github.com/micro/go-micro/v2/codec" "github.com/micro/go-micro/v2/codec/bytes" + "github.com/oxtoacart/bpool" "google.golang.org/grpc" "google.golang.org/grpc/encoding" ) @@ -23,6 +24,9 @@ type wrapCodec struct{ encoding.Codec } var jsonpbMarshaler = &jsonpb.Marshaler{} var useNumber bool +// create buffer pool with 16 instances each preallocated with 256 bytes +var bufferPool = bpool.NewSizedBufferPool(16, 256) + var ( defaultGRPCCodecs = map[string]encoding.Codec{ "application/json": jsonCodec{}, @@ -106,14 +110,19 @@ func (bytesCodec) Name() string { } func (jsonCodec) Marshal(v interface{}) ([]byte, error) { - if pb, ok := v.(proto.Message); ok { - s, err := jsonpbMarshaler.MarshalToString(pb) - - return []byte(s), err - } if b, ok := v.(*bytes.Frame); ok { return b.Data, nil } + + if pb, ok := v.(proto.Message); ok { + buf := bufferPool.Get() + defer bufferPool.Put(buf) + if err := jsonpbMarshaler.Marshal(buf, pb); err != nil { + return nil, err + } + return buf.Bytes(), nil + } + return json.Marshal(v) }