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
.
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program. The compiler performs optimization based on the knowledge it has of the program.
GCC has a range of optimization levels, plus individual options to enable or disable particular optimizations. The overall compiler optimization level is controlled by the command line option -On, where n is the required optimization level, as follows: -O0 . (default).
Defining Compiler Optimizations. An optimization is the process of transforming a piece of code into another functionally equivalent piece of code for the purpose of improving one or more of its characteristics. The two most important characteristics are the speed and size of the code.
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 inliningIf 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With