package pools
import (
"bytes"
"sync"
)
var bufPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func WithBuffer(fn func(*bytes.Buffer) error) error {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
defer bufPool.Put(b)
return fn(b)
}
For high-throughput endpoints that serialize JSON or build strings repeatedly, allocations can become a real cost. sync.Pool is a pragmatic tool for reusing temporary buffers without manual free lists. The key is to treat pooled objects as ephemeral: get a buffer, Reset it, use it, and return it. Never store pooled pointers long-term. The pool can drop objects at any time, which is fine because it’s a performance hint, not a correctness mechanism. In production, I use this for response building, log formatting, and compression pipelines where buffers are short-lived and frequently reused. It won’t fix slow algorithms, but it can significantly reduce allocs/op once you’ve identified a hot loop. Pair it with benchmarks so you can confirm the improvement.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
Rails.application.configure do
config.after_initialize do
Bullet.enable = true
Bullet.alert = false
Bullet.bullet_logger = true
Bullet.console = true
N+1 query detection with Bullet gem
Share this code
Here's the card — post it anywhere.