Showing posts with label golang_defer. Show all posts
Showing posts with label golang_defer. Show all posts

Sep 26, 2020

[Go] 'defer' optimizing notes

Proposal:
https://go.googlesource.com/proposal/+/refs/heads/master/design/34481-opencoded-defers.md


Optimizing:

  1. try not to run defer in a loop(for), which compiler will fallback to traditional defer chain implement
  2. try to have less exit point inside a function, which compiler will fallback to traditional defer chain implement


Proposal by Example:

defer f1(a)
if cond {
 defer f2(b)
}
body...
compiles to:
deferBits |= 1<<0
tmpF1 = f1
tmpA = a
if cond {
 deferBits |= 1<<1
 tmpF2 = f2
 tmpB = b
}

body...

exit:
if deferBits & 1<<1 != 0 {
 deferBits &^= 1<<1
 tmpF2(tmpB)
}

if deferBits & 1<<0 != 0 {
 deferBits &^= 1<<0
 tmpF1(tmpA)
}

[Go] inline gotya

Reference:
https://vsdmars.blogspot.com/2020/02/golang-tooling-update.html
https://github.com/golang/go/wiki/CompilerOptimizations
Proposal:
https://go.googlesource.com/proposal/+/refs/heads/master/design/34481-opencoded-defers.md


Function Inlining: (compiled with -gcflags="-m")
Only short and simple functions are inlined.
To be inlined a function must contain less than ~40 expressions(80 AST nodes)  and does not contain complex things like 
  • loops (for), 
  • labels, 
  • closures,
  • panic's,
  • recover's,
  • select's,
  • switch
  • defer (now up-lifted thanks to Proposal: Low-cost defers through inline code, and extra funcdata to manage the panic case)
  • go (goroutine creation)


Visualize with flag:
-gcflags="-d pctab=pctoinline"