var pool []Tree
to each of the stretch and long-lived closures in run(), pass &pool as the second argument to bottomUpTree(), pass pool as the second argument to itemCheck(). type Tree struct {
Left int
Right int
}
func itemCheck(id int, pool []Tree) uint32 {
tree := &pool[id]
if tree.Left != -1 && tree.Right != -1 {
return uint32(1) + itemCheck(tree.Right, pool) + itemCheck(tree.Left, pool)
}
return 1
}
func bottomUpTree(depth uint32, pool *[]Tree) int {
var tree Tree
if depth > uint32(0) {
tree.Left = bottomUpTree(depth-1, pool)
tree.Right = bottomUpTree(depth-1, pool)
} else {
tree.Left = -1
tree.Right = -1
}
id := len(*pool)
*pool = append(*pool, tree)
return id
}
func inner(depth, iterations uint32) string {
var (
pool []Tree
chk = uint32(0)
)
for i := uint32(0); i < iterations; i++ {
a := bottomUpTree(depth, &pool)
chk += itemCheck(a, pool)
pool = pool[:0]
}
return fmt.Sprintf("%d\t trees of depth %d\t check: %d",
iterations, depth, chk)
}
If it matters, your Go program can be made as fast as a C program.
What happens if you use
instead of
in the Go so it doesn't waste time growing tiny slices?