Optimized `go build` Jan. 17, 2026

Use this when releasing Go binaries!

The Script

Assuming you have command packages in cmd, you can write a build.sh like this:

#!/bin/sh
[ -d bin ] || mkdir bin
export CGO_ENABLED=0
exec go build -trimpath -ldflags="-s -w" -gcflags="-B" -o ./bin ./cmd/...

Execute it and you have optimized executables in bin.

This piece of script is in Public Domain.

Details

Param What it does How is it like
-trimpath Strips build paths from binaries Reproducible builds & smaller binaries.
-ldflags="-s -w" Strip debug symbols & DWARF Reduces binary size (~10–20 %).
-gcflags="-B" Enables the “branchless” compiler mode Faster compilation, slightly smaller binaries.

Feel free to adjust these parameters, like turning CGO_ENABLED=1 for projects depending on C libraries.

* The above is organized from part of a chat with gpt-oss (20b) about “Go performance tuning tips.”

Bonus

For amd64 builds, you can use GOAMD64=v3 to enable optimizations for modern CPU.

GOOS=linux GOARCH=amd64 GOAMD64=v3 go build ...

But the built executables will not run on old CPU.

Some systems already provide amd64v3 binary packages. You can do it too.