9.1.4 Tip #4 Loop Jamming

Loop jamming here refers to integrating the statements and operations from different loops to fewer loops or to one loop, thus reduce the number of loops in the code.

In some cases, several loops are implemented one by one. This may lead to a long list of iterations. In this case, loop jamming may help to increase the code efficiency by actually having the loops combined into one.

Loop Jamming reduces code size and makes code run faster as well by eliminating the loop iteration overhead. The table below shows the effect of loop jamming.

Table 9-5. Example of Loop Jamming
Separate loopsLoop jamming
C source code
#include <avr/io.h>
int main(void)
{
 uint8_t i, total = 0;
uint8_t tmp[10] = {0};
for (i=0; i<10; i++) {
 tmp [i] = ADCH;
}
for (i=0; i<10; i++) {
 total += tmp[i];
}
 UDR0 = total;
}
#include <avr/io.h>
int main(void)
{
uint8_t i, total = 0;
 uint8_t tmp[10] = {0};
for (i=0; i<10; i++)
{
 tmp [i] = ADCH;
 total += tmp[i];
 }
UDR0 = total;
}
AVR Memory Usage

Program: 164 bytes (2.0% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Program: 98 bytes (1.2% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Compiler optimization level-Os (Optimize for size)-Os (Optimize for size)