Rolled some loops to lower memory usage

Perf hit is negligible