Optimisation: What is Loop Unrolling

Loop unrolling is an optimisation designed to reduce theruntime of a program by trading off some code size.

The task of a Loop Unrolling optimisation is to take a loop for which there is a known number of steps and replace it with code for each one of those steps. effectively removing the loop and replacing it with direct linear code.

This produces faster code as it allows for the elimination of branches during the looping process which test for the end of loop state, as well as removing the counting arithmetic. Further to the benefits of removing the loop logic costs, it also allows for each instance of the loop to be considered alongside each other which opens up the possibility of further optimisations such as common subexpression elimination.

Example:

int val = 0;
for(int i = 0; i<3; i++)
val += i;

Becomes:

int val = 0;
val+=0
val+=1
val+=2

This example is trivial and in a real compiler would be further reduced by constant folding into a single value.