Logo von Go Optimizations

Go Optimizations

Community
v0lka
go-optimizations

Guides the agent to write and review performance-sensitive Go code by applying CPU cache awareness, false sharing prevention, instruction-level parallelism, data alignment, escape analysis, allocation reduction, inlining, profiling, GC tuning, and Docker/Kubernetes GOMAXPROCS configuration. Use when writing hot-path Go code, reviewing performance-critical sections, reducing allocations, profiling applications, tuning GC behavior, or deploying Go services in containers.

Übersicht

Herausgeberv0lka
Repositoryskills
Skill-Namego-optimizations
Sterne
28
Forks
1
Mitgelieferte Dateien
Nur Anweisungen
LizenzMIT
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • In sich abgeschlossen

    Alles, was das Modell braucht, steht in den Anweisungen — keine zusätzlichen Dateien zum Synchronisieren.

  • Open Source

    Von v0lka auf GitHub veröffentlicht. Prüfen Sie den Quellinhalt vor der Installation.

Installation

Installieren Sie den KI-Skill Go Optimizations in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner — liest SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-optimizations
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill anlegen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format lesen kann, kann diesen Skill nutzen — kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/v0lka/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/development/idiomatic-go/go-optimizations .claude/skills/go-optimizations
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Go Optimizations in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Go Optimizations automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Go Optimizations nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Keys.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

Go Optimization Patterns

"Make it correct, make it clear, make it concise, make it fast, in that order." -- Wes Dyer

Apply these rules only to performance-sensitive code paths. Do NOT sacrifice readability for micro-optimizations unless profiling shows a bottleneck.


1. CPU Cache Awareness

Cache Lines

A CPU fetches memory in 64-byte cache lines, not individual variables. One cache line holds 8 int64 values. Optimize data layout to maximize useful data per cache line.

Key rule: Iterating a slice where you skip elements is still fast if accesses fall within the same cache lines. The bottleneck is memory access, not iteration count.

Slice of Structs vs. Struct of Slices

When iterating over a single field across many records, a struct of slices provides better spatial locality than a slice of structs because the target field values are contiguous in memory.

go
// SLOWER when summing only field `a` -- fields interleaved in memory
type Foo struct {
    a int64
    b int64
}
func sumFoo(foos []Foo) int64 { /* iterates a, skips b, a, skips b... */ }

// FASTER -- all `a` values contiguous
type Bar struct {
    a []int64
    b []int64
}
func sumBar(bar Bar) int64 { /* iterates bar.a directly */ }

Use struct-of-slices layout when hot loops access only a subset of fields (column-oriented access pattern).

Predictability and Stride

  • Unit stride (contiguous elements): best -- predictable, minimal cache lines.
  • Constant stride (e.g., every 2nd element): predictable but less efficient.
  • Non-unit stride (linked list, slice of pointers): NOT predictable -- CPU cannot prefetch.

Prefer slices over linked lists and pointer-chasing structures in hot paths. Even if a linked list is allocated contiguously, the CPU cannot predict the access pattern.

Critical Stride (Cache Placement)

Modern caches are set-associative. When stride size equals the critical stride (number of cache sets x cache line size, typically 4 KB for an 8-way 32 KB L1D), all accessed blocks map to the same cache set, causing conflict misses.

Practical example: a matrix with exactly 512 int64 columns hits a critical stride on typical hardware. Using 513 columns avoids it and can be ~50% faster when reusing the same matrix.

Rule: When working with large matrices or strided access, avoid dimensions that are exact powers of 2 or multiples of the critical stride.


2. False Sharing

When two goroutines write to different variables that share the same cache line, the entire line is invalidated on each write across cores (MESI protocol). This is false sharing.

go
// BAD -- sumA and sumB likely share a cache line
type Result struct {
    sumA int64
    sumB int64
}

// GOOD -- padding forces separate cache lines
type Result struct {
    sumA int64
    _    [56]byte  // 64 - 8 = 56 bytes padding
    sumB int64
}

When to apply: any struct whose fields are written concurrently by different goroutines on hot paths. Alternative: use channels so goroutines communicate local results instead of sharing memory.


3. Instruction-Level Parallelism (ILP)

Modern CPUs execute independent instructions in parallel (superscalar). Data hazards (one instruction depends on the result of another) prevent parallelism.

Technique: introduce a temporary variable to break dependency chains so the CPU can execute more instructions in parallel.

go
// SLOWER -- s[0] increment must complete before checking s[0]
for i := 0; i < n; i++ {
    s[0]++
    if s[0]%2 == 0 {
        s[1]++
    }
}

// FASTER (~20%) -- v captures s[0], breaking the dependency chain
for i := 0; i < n; i++ {
    v := s[0]
    s[0] = v + 1
    if v%2 != 0 {  // note: check odd because v is pre-increment
        s[1]++
    }
}

Caveat: Go compiler output changes between versions. Verify with benchmarks and go build -gcflags "-S".


4. Data Alignment

The Go compiler adds padding to ensure each field's memory address is a multiple of its size. Poorly ordered struct fields waste memory.

Rule: sort struct fields by size in descending order.

go
// BAD -- 24 bytes (7 bytes padding after b1, 7 after b2)
type Foo struct {
    b1 byte   // 1 byte + 7 padding
    i  int64  // 8 bytes
    b2 byte   // 1 byte + 7 padding
}

// GOOD -- 16 bytes (only 6 bytes padding after b1+b2)
type Foo struct {
    i  int64  // 8 bytes
    b1 byte   // 1 byte
    b2 byte   // 1 byte + 6 padding
}

Compact structs reduce memory, improve cache utilization, and lower GC pressure when heap-allocated.


5. Stack vs. Heap and Escape Analysis

Stack allocation is nearly free and self-cleaning (no GC). Heap allocation requires GC work and is ~10x slower.

Escape Rules

PatternEscapes?
Returning a pointer to a local variable ("sharing up")Yes
Passing a pointer to a callee ("sharing down")No
Variable referenced after function returnsYes
Global variablesYes
Pointer sent to a channelYes
Variable referenced by a value sent to a channelYes
Local variable too large for the stackYes
Slice with runtime-determined length (make([]int, n))Yes
Backing array reallocated via appendMay escape
Slice with compile-time constant length (make([]int, 10))No (usually)

Verify assumptions: go build -gcflags "-m=2" shows escape decisions.

Do NOT return pointers "to avoid a copy" as a premature optimization. Copying within cache lines is extremely fast. Focus on readability and semantics first.


6. Reducing Allocations

API Design (Sharing Down)

Design APIs so callers provide buffers instead of functions returning new allocations:

go
// BAD -- returned slice escapes to heap
type Reader interface {
    Read(n int) ([]byte, error)
}

// GOOD -- caller provides the buffer (sharing down)
type Reader interface {
    Read(p []byte) (int, error)
}

Compiler Optimizations

The Go compiler avoids []byte to string conversion when used directly in a map lookup:

go
// SLOWER -- intermediate string variable forces allocation
key := string(bytes)
v, ok = m[key]

// FASTER -- compiler optimizes away the conversion
v, ok = m[string(bytes)]

sync.Pool

Use sync.Pool to reuse frequently allocated objects of the same type. It is NOT a cache (no size/capacity control); objects are drained each GC cycle.

go
var pool = sync.Pool{
    New: func() any {
        return make([]byte, 1024)
    },
}

func write(w io.Writer) {
    buf := pool.Get().([]byte)
    buf = buf[:0]           // reset before use
    defer pool.Put(buf)
    getResponse(buf)
    _, _ = w.Write(buf)
}

Other Allocation Reducers

  • Use strings.Builder instead of + for string concatenation.
  • Avoid unnecessary []byte to string conversions.
  • Preallocate slices and maps when length is known.
  • Use compact struct layout (see Data Alignment above).

7. Inlining

The Go compiler inlines functions below a complexity budget (~80 cost units). Inlining eliminates call overhead AND enables further optimizations (e.g., keeping variables on the stack).

Fast-Path Inlining

Extract the slow path into a separate function so the main function stays within the inlining budget:

go
// The Lock method stays small enough to inline
func (m *Mutex) Lock() {
    if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
        return  // fast path -- inlined
    }
    m.lockSlow()  // slow path -- separate function
}

func (m *Mutex) lockSlow() {
    // complex logic that exceeds inlining budget
}

Check inlining decisions: go build -gcflags "-m=2" reports which functions are inlined and which exceed the budget.


8. Go Diagnostics Tooling

Profiling with pprof

Enable via import _ "net/http/pprof" (safe for production; CPU profile only runs when activated).

ProfileEndpointWhat It Shows
CPU/debug/pprof/profile?seconds=30Where the app spends CPU time
Heap/debug/pprof/heap?gc=1Current heap allocations
Allocs/debug/pprof/allocsAll past heap allocations
Goroutine/debug/pprof/goroutine/?debug=0Stack traces of all goroutines
Block/debug/pprof/blockWhere goroutines block on sync primitives
Mutex/debug/pprof/mutexMutex contention

Key signals from CPU profile:

  • Excessive runtime.mallogc => too many small heap allocations.
  • Time in channel/mutex ops => excessive contention.
  • Time in syscall.Read/syscall.Write => improve I/O buffering.

Memory leak detection:

  1. GET /debug/pprof/heap?gc=1 (forces GC first)
  2. Wait
  3. GET /debug/pprof/heap?gc=1 again
  4. go tool pprof -http=:8080 -diff_base <file2> <file1>

Important: enable only ONE profiler at a time to avoid erroneous observations.

Block and mutex profiles must be explicitly enabled:

  • runtime.SetBlockProfileRate(rate)
  • runtime.SetMutexProfileFraction(rate)

Execution Tracer

bash
go test -bench=. -trace=trace.out
go tool trace trace.out

Shows: goroutine scheduling, GC phases, parallelism quality. Use runtime/trace for user-defined tasks:

go
ctx, task := trace.NewTask(context.Background(), "myTask")
trace.WithRegion(ctx, "main", func() {
    // work
})
task.End()

CPU profiling vs tracing: profiling is sample-based per-function (10ms granularity); tracing is event-based per-goroutine (no rate bound).


9. Garbage Collector Tuning

Go GC is concurrent mark-and-sweep. Controlled by GOGC (default: 100), which sets heap growth percentage before next GC. A GC also runs if none has triggered in 2 minutes.

ScenarioRecommendation
Steady load increaseGOGC=100 is fine
Sudden traffic spikeIncrease GOGC to reduce GC frequency during ramp
Extreme spike (seconds)Pre-allocate a large byte slice to raise the heap floor

Pre-allocation trick for extreme spikes:

go
// In main.go -- lazy allocation via mmap, no physical memory until used
var _ = make([]byte, 1_000_000_000) // 1 GB virtual reservation

This raises the GC trigger threshold (next GC at 2 GB if GOGC=100) without consuming physical memory.

Debug GC: GODEBUG=gctrace=1 go test -bench=. -v


10. Go in Docker and Kubernetes

GOMAXPROCS defaults to the host's logical CPU count, NOT the container's CPU limit. With a 4-core limit on an 8-core host, Go spawns 8 OS threads. CFS (Completely Fair Scheduler) throttles after the quota is consumed, causing up to 300% latency penalty.

Example: 8 threads x 50ms = 400ms quota consumed in 50ms, application paused for remaining 50ms.

Fix: use go.uber.org/automaxprocs:

go
import _ "go.uber.org/automaxprocs"

This automatically sets GOMAXPROCS to match the container CPU quota, preventing CFS throttling.

Track: Go issue #33803 for native CFS awareness.

Häufig gestellte Fragen

Was macht der KI-Skill Go Optimizations?

Guides the agent to write and review performance-sensitive Go code by applying CPU cache awareness, false sharing prevention, instruction-level parallelism, data alignment, escape analysis, allocation reduction, inlining, profiling, GC tuning, and Docker/Kubernetes GOMAXPROCS configuration. Use when writing hot-path Go code, reviewing performance-critical sections, reducing allocations, profiling applications, tuning GC behavior, or deploying Go services in containers.

Warum Go Optimizations in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Go Optimizations besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Go Optimizations in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-optimizations ein. TypingMind liest die Datei SKILL.md und installiert den Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Go Optimizations nutzen?

Jedes Modell, das Sie in TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Go Optimizations verwenden?

So viele Sie möchten. Solange ein Modell Skills unterstützt, können Sie Go Optimizations damit verwenden – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama und weitere – alles in TypingMind mit Ihren eigenen API-Schlüsseln.

Ist der KI-Skill Go Optimizations kostenlos?

Ja. Der Skill wird von v0lka auf GitHub unter der Lizenz MIT veröffentlicht. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: eine Datei namens SKILL.md mit einem Namen und einer Beschreibung sowie allen Skripten, Vorlagen oder Referenzdateien, die das Modell möglicherweise benötigt. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und benötigen daher weder Server noch API-Schlüssel oder Laufzeitumgebung. Sie funktionieren mit jedem Modell.

Alle

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇