Change loop order to improve cache locality