...

/

Tips on Compiler Optimization

Tips on Compiler Optimization

Useful tips and tricks for programming in Go.

Compiler Optimizations

You can pass specific compiler flags to see what optimizations are being applied as well as how some aspects of memory management. This is an advanced feature, mainly for people who want to understand some of the compiler optimizations in place.

Let’s take the following code example from an earlier chapter:

Press + to interact
package main
import "fmt"
type User struct {
Id int
Name, Location string
}
func (u *User) Greetings() string {
return fmt.Sprintf("Hi %s from %s",
u.Name, u.Location)
}
func NewUser(id int, name, location string) *User {
id++
return &User{id, name, location}
}
func main() {
u := NewUser(42, "Matt", "LA")
fmt.Println(u.Greetings())
}

Build your file (here called t.go) passing some gcflags:

Press + to interact
$ go build -gcflags=-m t.go
# command-line-arguments
./t.go:15: can inline NewUser
./t.go:21: inlining call to NewUser
./t.go:10: leaking param: u
./t.go:10: leaking param: u
./t.go:12: (*User).Greetings ... argument does not escape
./t.go:15: leaking param: name
./t.go:15: leaking param: location
./t.go:17: &User literal escapes to heap
./t.go:15: leaking param: name
./t.go:15: leaking param: location
./t.go:21: &User literal escapes to heap
./t.go:22: main ... argument does not escape

The compiler notices that it can inline the NewUser function defined on line 15 and inline it on line 21. Dave Cheney has a great post about why Go’s inlining is helping your programs run faster. ...

Access this course and 1400+ top-rated courses and projects.