March 29, 2008

Create variables when they are needed and assign values immediately

As a common habit from C users, people usually create variables and then use them later in the scope. This is not a mistake of course but there is a better way to do this in C++ if runtime speed is important.

{
my_class my_var;
.... // my_var is not used here
my_class my_var = my_object
....
}

Above is an example bad use of a variable. We can count on compilers to optimize this. Do you know what is wrong here? Nothing is wrong. The only thing is there are two steps (constructor and assignment) to generate my_var. This can be done in one step and can be created as late as possible

{
...
my_class my_var = my_object;
...
}

Above is a better example if you need a faster code when running. Because we constructed our object in one step.

Hope this helps,
Burak

March 15, 2008

Prefer pre-increment to post-increment

Post-increment operator uses an extra memory space for copy of the object. That means extra time is required. There are some cases you might prefer post-increment to pre-increment but for one line operations, prefer pre-increment to post increment. Here is an example

for(int i = 0; i < max; ++i) // i++ should be avoided
{
// Do some stuff
}
...
++index; // index++; should be avoided
...

A case you might prefer post increment:

a = b++; // a = b; ++b; should be avoided. a = b; b++; should also be avoided

Actually, most compilers do this optimisations automatically but some might not. So it is better to write code optimised :)