Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Last active August 8, 2025 21:39
Show Gist options
  • Select an option

  • Save mdwhatcott/0af87d27a4597745fd96d097416b6156 to your computer and use it in GitHub Desktop.

Select an option

Save mdwhatcott/0af87d27a4597745fd96d097416b6156 to your computer and use it in GitHub Desktop.
Code Samples: Careful Object Pooling and Reuse
package main
import (
"bytes"
"fmt"
"runtime"
)
func main() {
ch := make(chan *bytes.Buffer)
go write(ch)
read(ch)
}
func write(out chan *bytes.Buffer) {
defer close(out)
for range 10 {
out <- bytes.NewBufferString(randomKey())
}
}
func read(in chan *bytes.Buffer) {
for b := range in {
content := b.Bytes()
runtime.Gosched() // simulate some minimal processing
s := string(content)
if _, ok := valid[s]; !ok {
fmt.Println("invalid key:", s)
}
}
}
func randomKey() string {
for key := range valid {
return key
}
panic("no values")
}
var valid = map[string]struct{}{
"A": {},
"BB": {},
"CCC": {},
}
package main
import (
"bytes"
"fmt"
"runtime"
"sync"
)
func main() {
pool := &sync.Pool{
New: func() any { return bytes.NewBuffer(nil) },
}
ch := make(chan *bytes.Buffer)
go write(pool, ch)
read(pool, ch)
}
func write(pool *sync.Pool, out chan *bytes.Buffer) {
defer close(out)
for range 10 {
b := pool.Get().(*bytes.Buffer)
b.Reset()
b.WriteString(randomKey())
out <- b
}
}
func read(pool *sync.Pool, in chan *bytes.Buffer) {
for b := range in {
content := b.Bytes()
pool.Put(b)
runtime.Gosched() // simulate some minimal processing
s := string(content)
if _, ok := valid[s]; !ok {
fmt.Println("invalid key:", s)
}
}
}
func randomKey() string {
for key := range valid {
return key
}
panic("no values")
}
var valid = map[string]struct{}{
"A": {},
"BB": {},
"CCC": {},
}
package main
import (
"bytes"
"fmt"
"io"
"runtime"
"sync"
)
func main() {
pool := &sync.Pool{
New: func() any { return bytes.NewBuffer(nil) },
}
ch := make(chan *bytes.Buffer)
go write(pool, ch)
read(pool, ch)
}
func write(pool *sync.Pool, out chan *bytes.Buffer) {
defer close(out)
for range 10 {
b := pool.Get().(*bytes.Buffer)
b.Reset()
b.WriteString(randomKey())
out <- b
}
}
func read(pool *sync.Pool, in chan *bytes.Buffer) {
buffer := bytes.NewBuffer(nil)
for b := range in {
buffer.Reset()
_, _ = io.Copy(buffer, b)
pool.Put(b)
content := buffer.Bytes()
runtime.Gosched() // simulate some minimal processing
s := string(content)
if _, ok := valid[s]; !ok {
fmt.Println("invalid key:", s)
}
}
}
func randomKey() string {
for key := range valid {
return key
}
panic("no values")
}
var valid = map[string]struct{}{
"A": {},
"BB": {},
"CCC": {},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment