Optimize the tree-walking code

Apparently these analyze trees can be rather large so this was a major
perf bottleneck. Still is somewhat, but much better now.