C optimisations

Labels: , , , , |

Using array indices

If you wished to set a variable to a particular character, depending upon the value of something, you might do this :

switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
or maybe
if ( queue == 0 )
letter = 'W';
else if ( queue == 1 )
letter = 'S';
else
letter = 'U';
A neater ( and quicker ) method is to simply use the value as an index into a character array, eg.
static char *classes="WSU";

letter = classes[queue];
--------------------------------------------------------------------------------
Aliases

Consider the following:
void func1( int *data )
{
int i;

for(i=0; i<10;>
{
somefunc2( *data, i);
}
}
Even though "*data" may never change, the compiler does not know that somefunc2() did not alter it, and so the program must read it from memory each time it is used - it may be an alias for some other variable that is altered elsewhere. If you know it won't be altered, you could code it like this instead:
void func1( int *data )
{
int i;
int localdata;

localdata = *data;
for(i=0; i<10;>
{
somefunc2( localdata, i);
}
}
This gives the compiler better opportunity for optimisation.

--------------------------------------------------------------------------------

Integers

Use unsigned ints instead of ints if you know the value will never be negative. Some processors can handle unsigned integer arithmetic considerably faster than signed ( this is also good practise, and helps make for self-documenting code).
So the best declaration for an int variable in a tight loop would be

register unsigned int var_name;

(although it is not guaranteed that the compiler will take any notice of "register", and "unsigned" may make no difference to the processor.)

Remember, integer arithmetic is much faster than floating-point arithmetic, as it can be usually be done directly by the processor, rather than relying on external FPUs or floating point maths libraries. If you only need to be accurate to two decimal places (e.g. in a simple accounting package), scale everything up by 100, and convert it back to floating point as late as possible.

0 comments: