Performance

suggest change

Writing high-performance Go code requires understanding how Go allocates memory, handles garbage collection, and schedules goroutines. Optimization should always be guided by empirical measurements using Go's built-in benchmarking and profiling tools.

Benchmark Before Optimizing

Always measure performance with benchmarks before and after changes:

package mypkg

import "testing"

func BenchmarkStringConcat(b *testing.B) {
	b.ReportAllocs() // Reports allocations per operation
	for i := 0; i < b.N; i++ {
		s := ""
		for j := 0; j < 100; j++ {
			s += "a"
		}
	}
}

Run benchmarks with:

go test -bench=. -benchmem

Minimizing Allocations: Stack vs. Heap

Memory allocated on the stack is practically free (deallocated automatically when the function returns). Memory that escapes to the heap requires Garbage Collector (GC) tracking and cleanup.

Check escape analysis decisions with -gcflags="-m":

go build -gcflags="-m" main.go

Common causes of heap escape:

Pre-allocating Slices and Maps

Growing a slice dynamically forces repeated memory reallocations and array copying. When the required capacity is known or can be estimated, pre-allocate it with make:

// Inefficient: Repeated slice growth and copying
items := make([]int, 0)
for i := 0; i < 10000; i++ {
	items = append(items, i)
}

// Optimized: Exactly 1 heap allocation
items = make([]int, 0, 10000)
for i := 0; i < 10000; i++ {
	items = append(items, i)
}

// Similarly for maps: provides an initial hash table sizing hint
lookup := make(map[string]int, 5000)

Efficient String Construction with strings.Builder

Strings in Go are immutable. Chaining + operators creates a new string on each concatenation. Use strings.Builder, which minimizes allocations by growing an internal byte buffer:

package main

import "strings"

func buildSentence(words []string) string {
	var sb strings.Builder

	// Pre-grow buffer capacity if total size can be estimated
	sb.Grow(len(words) * 8)

	for i, w := range words {
		if i > 0 {
			sb.WriteString(" ")
		}
		sb.WriteString(w)
	}

	return sb.String()
}

Object Reuse with sync.Pool

For short-lived objects allocated frequently in concurrent request loops (such as serialization buffers), use sync.Pool to relieve GC pressure:

package main

import (
	"bytes"
	"sync"
)

var bufferPool = sync.Pool{
	New: func() any {
		return new(bytes.Buffer)
	},
}

func formatMessage(user string, id int) []byte {
	buf := bufferPool.Get().(*bytes.Buffer)
	buf.Reset() // Always reset before reuse
	defer bufferPool.Put(buf)

	buf.WriteString("User: ")
	buf.WriteString(user)
	buf.WriteString(" processed")

	// Return a copy if the data must outlive the buffer
	result := make([]byte, buf.Len())
	copy(result, buf.Bytes())
	return result
}

Use Atomics for High-Contention Counters

For simple metrics and shared counters across goroutines, sync/atomic performs significantly faster than acquiring and releasing a sync.Mutex:

package main

import (
	"sync/atomic"
)

type Metrics struct {
	requestCount atomic.Uint64
}

func (m *Metrics) RecordRequest() {
	m.requestCount.Add(1)
}

func (m *Metrics) Total() uint64 {
	return m.requestCount.Load()
}

Key Optimization Rules

  1. Avoid premature optimization: Write clear, idiomatic code first.
  2. Profile real workloads: Use pprof CPU and heap profiles to locate actual bottlenecks.
  3. Control goroutine fan-out: Avoid spawning unbounded goroutines per request; use worker pools or semaphores to cap concurrency.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents