Move the computation of some values out of loops so that they're not constantly recalculated even when they don't change.