From 3035221cb1045a6fd82469a8781ad3b759ec5c7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Paj=C4=85k?= Date: Thu, 25 Jan 2024 11:27:46 +0100 Subject: [PATCH] Fix sync.Pool example --- .../96-reduce-allocations/sync-pool/main.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/12-optimizations/96-reduce-allocations/sync-pool/main.go b/src/12-optimizations/96-reduce-allocations/sync-pool/main.go index 9bab3dc..90861f8 100644 --- a/src/12-optimizations/96-reduce-allocations/sync-pool/main.go +++ b/src/12-optimizations/96-reduce-allocations/sync-pool/main.go @@ -7,17 +7,21 @@ import ( var pool = sync.Pool{ New: func() any { - return make([]byte, 1024) + b := make([]byte, 1024) + return &b }, } func write(w io.Writer) { - buffer := pool.Get().([]byte) - buffer = buffer[:0] - defer pool.Put(buffer) + bPtr := pool.Get().(*[]byte) + defer func() { + *bPtr = (*bPtr)[:0] + pool.Put(bPtr) + }() - getResponse(buffer) - _, _ = w.Write(buffer) + b := *bPtr + getResponse(b) + _, _ = w.Write(b) } func getResponse([]byte) {