From 04d8349a6c4f1ae240767d53534d9f64faa2fa49 Mon Sep 17 00:00:00 2001 From: Graham McIntire Date: Thu, 12 Feb 2026 09:55:38 -0600 Subject: [PATCH] pool protobuf marshal buffers to reduce allocations Use sync.Pool to reuse 4KB byte slices for protobuf marshaling via MarshalAppend instead of allocating fresh buffers per result message. Reduces GC pressure under high-throughput polling. --- agent.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/agent.go b/agent.go index b5773ab..67f01d5 100644 --- a/agent.go +++ b/agent.go @@ -118,13 +118,20 @@ func runSession(ctx context.Context, baseURL, token string) error { } } + bufPool := &sync.Pool{ + New: func() any { return make([]byte, 0, 4096) }, + } + sendBinaryResult := func(event string, msg proto.Message) { - bin, err := proto.Marshal(msg) + buf := bufPool.Get().([]byte)[:0] + bin, err := proto.MarshalOptions{}.MarshalAppend(buf, msg) if err != nil { slog.Error("marshal protobuf", "error", err) return } - payload, _ := json.Marshal(map[string]string{"binary": base64.StdEncoding.EncodeToString(bin)}) + encoded := base64.StdEncoding.EncodeToString(bin) + bufPool.Put(bin[:0]) + payload, _ := json.Marshal(map[string]string{"binary": encoded}) sendMsg(event, payload) }