The Wayback Machine - https://web.archive.org/web/20240118175334/https://www.geeksforgeeks.org/loop-unrolling/
Open In App
Related Articles

Loop Unrolling

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Loop unrolling is a loop transformation technique that helps to optimize the execution time of a program. We basically remove or reduce iterations. Loop unrolling increases the program’s speed by eliminating loop control instruction and loop test instructions.

Program 1:




// This program does not uses loop unrolling.
#include<stdio.h>
  
int main(void)
{
    for (int i=0; i<5; i++)
        printf("Hello\n"); //print hello 5 times
  
    return 0;
} 


Program 2:




// This program uses loop unrolling.
#include<stdio.h>
  
int main(void)
{
    // unrolled the for loop in program 1
    printf("Hello\n");
    printf("Hello\n");
    printf("Hello\n");
    printf("Hello\n");
    printf("Hello\n");
  
    return 0;
} 


Output:

Hello
Hello
Hello
Hello
Hello

Illustration:
Program 2 is more efficient than program 1 because in program 1 there is a need to check the value of i and increment the value of i every time round the loop. So small loops like this or loops where there is fixed number of iterations are involved can be unrolled completely to reduce the loop overhead.

Advantages:

  • Increases program efficiency.
  • Reduces loop overhead.
  • If statements in loop are not dependent on each other, they can be executed in parallel.

Disadvantages:

  • Increased program code size, which can be undesirable.
  • Possible increased usage of register in a single iteration to store temporary variables which may reduce performance.
  • Apart from very small and simple codes, unrolled loops that contain branches are even slower than recursions.

Reference:
https://en.wikipedia.org/wiki/Loop_unrolling


Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 11 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads