Thursday, November 18, 2010

Efficiency of Increment and Decrement Operators

By the name of God, most merciful and most gracious, I will inaugurate the first post of this blog ever.

As suggested by the title above, this post will discuss, albeit briefly, a little efficiency factor seldom optimized by programmers and engineers everywhere: The Increment (++) and Decrement (--) operators.

int x=1;
x++;
++x;

Both of these forms of incrementing the value of the variable x do act correctly, but is there any difference?

The way x++ works is the following: create temporary x, increment temporary x, return temporary x.
As for ++x: increment x, return x


Note that this tip concerns standalone ++ operator calls

If the ++ operator is used for trivial types such as int and double, then the performance will not take a hit if x++ is used instead of ++x.

But for non-trivial types, like bigger objects, the ++ operator can differ a lot. A certain object that overrides the ++ operator might be large in size, and so creating a copy of it might hurt performance. In such case using ++x is better.

Embedded systems and mobile platforms are devices that can benefit a lot from good use of the ++ operator.

No comments:

Post a Comment