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 :)

1 comment:

Bennett said...

Good point. I have also written about this and other reasons to prefer prefix operators over postfix.