Apr 19, 2020

[Go] Micro optimizing Go Code (2018 GopherCon)

Micro optimizing Go Code
https://www.youtube.com/watch?v=keydVd-Zn80

Benchmarking tools:
https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go
https://godoc.org/golang.org/x/perf/cmd/benchstat
https://golang.org/pkg/net/http/pprof/
https://golang.org/pkg/runtime/pprof/

Consider writing a function which can be inlined.

This will show which functions are not able getting inlined:
$ go test -gcflags="-m=2" 2>&1 | ag "too complex"


Inlining rules in Go:
1. No nonlinear control flow:
    for, range, select, break, defer, type switch
2. No recover(ok with panic)
3. No certain runtime funcs and no non-intrinsic assembly
go compiler internal: inl.go


Consider writing code avoid index boundary check.
This will show where BCE occured:
$ go test -gcflags="-d=ssa/check_bce/debug=1"

BCE:
http://vsdmars.blogspot.com/search/label/golang_runtime_bce

Optimizing table lookup (all old-school opt from C++/C):
1. propagate constants
2. unroll loops
3. reuse previously-allocated local variables
4. reduce indirection
5. Consider using array instead of slice(Go specific)

Reuse the slice. (sliceForAppend, also consider using sync.Pool 
http://vsdmars.blogspot.com/2020/04/go-use-syncpool-with-sense.html)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.