low-level optimization to reduce stack usage & accelerate calculations

This is the rest of former #759.