1

original code

while(i<30){
// do something
i++;
}

unrolled while loop

while(i<15){
// do something twice
i+=2;
}

Cant we unroll it as shown above. Do we always have to do it like http://en.wikipedia.org/wiki/Loop_unrolling ?

klijo
  • 15,761
  • 8
  • 34
  • 49

1 Answers1

2

In general, the answer is no. It works for 30 and 15 because 30 is even, but it would not work as easily for odd numbers. "Duff's device" was invented to deal with general case. It is quite ugly, though.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • so then not only for while loops. For for loops too this matters if the iteration does not happen for even numbers right ? – klijo Dec 28 '11 at 22:50
  • 1
    @klijo This is correct: when the desired number of iterations is not a multiple of the number of times you unroll, you need to complete the remaining `n%k` iterations manually or in a tight loop without unrolling. – Sergey Kalinichenko Dec 29 '11 at 00:24