'Passing an optimization flag to a Go compiler?

To compile a Go program you type go build myprogram.go, can you pass an optimization flags along or the code is always compiled in the same way? I am talking about speed optimizations, code size optimizations or other optimizations.

I know if you use gccgo you just pass -O2 or -O0 but my question is about an official Go compiler go.



Solution 1:[1]

Actually no explicit flags, this Go wiki page lists optimizations done by the Go compiler and there was a discussion around this topic in golang-nuts groups.

You can turn off optimization and inlining in Go gc compilers for debugging.

-gcflags '-N -l'
  • -N : Disable optimizations
  • -l : Disable inlining

Solution 2:[2]

If you're looking to optimize the binary size, you can omit the symbol table, debug information and the DWARF symbol table by passing -s and -w to the Go linker:

$ go build -o mybinary -ldflags="-s -w" src.go

(source blog post which includes some benchmarks)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Azeem
Solution 2 fstanis