Thursday, October 7, 2010

Optimal Arithmetic Operations

While we write programs, we usually think in terms of the decimal number system. It may seem normal to us, but the computer prefers binary. So doing arithmetic operations that are more binary friendly will help optimize your program.

It is better to multiply and divide by a power of two rather than some other number. Obviously this should only be done when it does not affect the program execution. The optimization achieved here is because the compiler will replace the division instruction with a shift instruction, which in many processors can be completed in half clock cycle. This is similar to the division and multiplication of a number by 10 in the decimal system.

A more optimized code can also be obtained by using an int (4 bytes/1 word) rather than a char or a byte, even if your data will fit into 1 byte. This is because many compilers will first convert a char or byte to an int while doing the arithmetic operations and then convert it back again. This leads to slow program execution.

No comments:

Post a Comment