Tag Archive: Optimization in C++


Loop Unrolling

Consider the following code:
int *buff = new int[3];
for (int i =0; i<3; i++)
buff[i] = 0;
This loop is inefficient: 🙂
On every iteration, it assigns a value to the next array element. However,precious CPU time is also wasted on testing the counter and incrementing the counter’s value and performing a jump statement. To avoid this overhead, the compiler can unroll the loop into a sequence of three assignment statements, as follows:
buff[0] = 0;
buff[1] = 0;
buff[2] = 0;

for https://vctipsplusplus.wordpress.com/

BijU

If your actions inspire others to dream more, learn more, do more and become more, you are a leader

Advertisements

Some Optimized Codes

Different types of optimization help us to improve our code’s stability.

Tail splitting eliminates jumps by bringing common return statements into the blocks, so that

if(x) {
   b = 1;
} else {
   b = 2;
}
return b;

becomes

if(x) {
   b = 1;
   return b;
} else {
   b = 2;
   return b;
}

which is a speed optimization.

Tail merging, on the other hand, pulls duplicate instructions out of the blocks, which is a size optimization. Tail merging turns the following:

if(x) {
   bar()
   b = 1;
} else {
   foo()
   b = 1;
}

into this:

if(x) {
   bar()
} else {
   foo()
}
b = 1;