Optimizations in the algorithm that builds loops