backport optimizations from thapster branch