> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trykode.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Optimize Code Performance with Kode Golf

> Kode Golf uses parallel Ghost Branch worktrees to apply competing optimization strategies to a file, benchmarks them, and merges the best-performing version.

`kode golf` is a competitive optimization command: you point it at a single source file, and it spins up three isolated git worktrees that each attempt a different optimization strategy in parallel. All three are benchmarked against the original baseline, and the version that shows the most improvement is offered to you for merge. If no strategy beats the baseline, your original code is left completely untouched.

## How it works

<Steps>
  ### Baseline measurement

  Before generating any changes, Kode runs your benchmark command against the original file and records the results — `ns/op`, `B/op`, and `allocs/op` for each benchmark function. This is the bar every strategy must beat.

  ### Three parallel strategies

  Kode creates three isolated git worktrees and generates a separate optimized version of your file in each, using a different strategy prompt:

  * **Concurrency** — goroutines, channels, async patterns, and parallel fan-out to reduce wall-clock time
  * **Memory** — pre-allocation, stack-vs-heap placement, reduced copies, and buffer reuse to shrink allocation pressure
  * **Algorithmic** — Big-O reduction, hash-map lookups over linear scans, loop elimination, and early-exit conditions

  Each strategy generates a set of structured hunks, passes them through the full verification gate (syntax, imports, calls, architecture), and only applies the hunks that pass. A strategy that fails verification is marked as failed and excluded from scoring.

  ### Benchmarking and scoring

  After the optimized code is applied in each worktree, Kode runs the benchmark command in each worktree and compares results against the baseline. A strategy's score reflects how many benchmark functions improved and by how much.

  ### Merge the winner

  Kode prints a results table showing each strategy's per-benchmark delta and asks whether you want to merge the winning version. If you decline, or if no strategy improved the baseline, your original file is left completely untouched.
</Steps>

## Usage

<CodeGroup>
  ```bash Optimize for speed (default) theme={null}
  kode golf internal/parser/parser.go
  ```

  ```bash Optimize for memory theme={null}
  kode golf --optimize memory pkg/cache/lru.go
  ```

  ```bash Optimize for algorithmic complexity theme={null}
  kode golf --optimize complexity pkg/search/index.go
  ```
</CodeGroup>

## Flags

| Flag             | Description                                             | Default                                      |
| ---------------- | ------------------------------------------------------- | -------------------------------------------- |
| `--optimize`     | Optimization target: `speed`, `memory`, or `complexity` | `speed`                                      |
| `--model`        | LLM model override                                      | from `kode.json`                             |
| `--test-command` | Benchmark command                                       | auto-detected (`go test -bench=. -benchmem`) |
| `--project-dir`  | Project root directory                                  | current working directory                    |

## Example output

```
── Code Golf ────────────────────────────────────────
  File: internal/parser/parser.go
  Target: speed | Strategies: concurrency, memory, algorithmic
  LLM: anthropic/claude-sonnet-4-6 | Test: go test -bench=. -benchmem

── Results ──────────────────────────────────────────
  Baseline — 3 benchmark(s)
    BenchmarkParse:      1842.00 ns/op (512 B/op, 8 allocs/op)
    BenchmarkParseJSON:   934.00 ns/op (256 B/op, 4 allocs/op)
    BenchmarkParseYAML:  3210.00 ns/op (1024 B/op, 16 allocs/op)

  ✓ concurrency (ghost-alpha) 👑 WINNER
    Improvement: +3/3 benchmarks (+100%)
      BenchmarkParse:      1104.00 ns/op [⬇ 40% faster]
      BenchmarkParseJSON:   701.00 ns/op [⬇ 25% faster]
      BenchmarkParseYAML:  1987.00 ns/op [⬇ 38% faster]

  ✓ memory (ghost-beta)
    Improvement: +1/3 benchmarks (+33%)
      BenchmarkParse:      1798.00 ns/op
      BenchmarkParseJSON:   880.00 ns/op [⬇  6% faster]
      BenchmarkParseYAML:  3310.00 ns/op [⬆  3% slower]

  ✗ algorithmic (ghost-gamma)
    Failed verification

✓ Winner: concurrency (ghost-alpha)
  Benchmark improvement: +100% of benchmarks

  Merge optimized version? [Y/n]:
```

## Best use cases

Code Golf is most effective when you already suspect a specific file is a bottleneck:

* **Hot paths** — a function that is called millions of times per request and shows up in profiles
* **Algorithms you know are slow** — O(n²) loops, repeated string concatenation, linear searches over large slices
* **Memory-intensive data structures** — caches, buffers, and pools that allocate on every call
* **Parsers and serializers** — files that transform large inputs and are called on every request

Avoid running Golf on files that are primarily I/O-bound (network calls, database queries) — the LLM-generated strategies optimise CPU and memory patterns and will not improve latency caused by external systems.

## Benchmark commands for non-Go projects

The default benchmark command is `go test -bench=. -benchmem`. For other languages, pass `--test-command` with an equivalent:

<CodeGroup>
  ```bash Node.js / Bun theme={null}
  kode golf --test-command "npm run bench" src/parser/index.ts
  ```

  ```bash Python (pytest-benchmark) theme={null}
  kode golf --test-command "pytest --benchmark-only" src/parser.py
  ```

  ```bash Rust theme={null}
  kode golf --test-command "cargo bench" src/parser.rs
  ```
</CodeGroup>

<Note>
  The benchmark command must write results to stdout in a format Kode can parse. For Go this is automatic. For other runtimes, Kode reads raw stdout and compares the numeric throughput figures between runs — any benchmark framework that prints numbers works, but structured output (JSON, TAP) gives cleaner comparisons.
</Note>

<Tip>
  Run `kode plan --graph "<task>"` on the file before golfing to understand its blast radius — how many other files import it and could be affected by a change. A file with a blast radius of 10+ is a good candidate for caution: the benchmark might improve but callers may rely on specific allocation behaviour or ordering that changes under the algorithmic strategy.
</Tip>

## Next steps

<CardGroup cols={2}>
  <Card title="Loop Mode" icon="arrows-rotate" href="/guides/loop-mode">
    Run the full pipeline with test execution, rollback, and multi-strategy Ghost Branches.
  </Card>

  <Card title="Daemon Mode" icon="robot" href="/guides/daemon-mode">
    Let Kode watch your git history and proactively surface performance regressions as they accumulate.
  </Card>
</CardGroup>
