A few performance optimizations...

...mostly by avoiding doing the same calculations over and over again.