Coding Guidelines
Generic Guidelines
Performance
<- ^ ->
<< ^^ >>

Design performance into your code from the beginning, and tune your code to improve it.

Design in performance Choosing the right data structures and algorithms is the most important aspect of good performance. The best way to speed up code is to eliminate it.
Conduct Performance Analysis You need hard data to solve performance problems. Measure your code to find out what can be improved.
Use cached objects Creating and destroying objects can take a lot of time; consider holding onto objects for longer periods and reusing them.
Move Code Out of Loops A simple optimization is to move code out of loops. One key is to look for expressions which do not depend on the loop index and operations which generate the same results on every iteration. Removing code from loops, especially nested loops, helps improve speed.
pointer = buffer + 20;
while ( buffer < pointer )
{
    y = x * 5;
    *(pointer--) = x * y;
}

In the preceding example two expressions may be moved outside of the while loop without changing the validity of the loop.

y = x * 5;
temp = x * y;
pointer = buffer + 20;
while ( buffer < pointer )
{
    *(pointer--) = temp;
}
Reorder Logical Expression Tests The logical AND (&&) and logical OR (||) operations are short-circuited in the C language. That is, the evaluation of each operand is only done until the validity (true or false) of the expression is determined. Therefore, the second operand of an AND operation will not be evaluated if the first operand is false because the result is assured to be false. In the same manner, the second operand of the OR operation is not evaluated if the first one is true since this assures the result to be true. By taking advantage of this knowledge the programmer can order the operands such that the first operand will most likely be true in an OR operation and false in an AND operation. Also (as with repetitive computations) if a logical expression appears multiple times within a function the code should be reworked to evaluate it once and save the logical results in a temporary location. This can save time, especially with large logical expressions.

Additionally, the programmer should apply the Distributivity Property to logical expression tests whenever possible. For example, assuming three knowns; m, n, and p for equivalent logical expressions follow:

((n || m) && (n || p))   equals   (n || (m && p))
((n && m) || (n && p))   equals   (n && (m || p))
((n || m) || (n || p))   equals   (n || (m || p))
((n && m) && (n && p))   equals   (n && (m && p))

As is obvious, all of the equivalent expressions on the right of "equals" requires one less expression evaluation than those on the left.


<- ^ ->
<< ^^ >>
Last modified: 25 May 2009
copyright 2004 Bear Consulting Group