| « Variable Usage And Meanings | Code Performance » |
i++ vs. ++i
So, I’ve been “told” in the past that I should never use a pre-increment operator or pre-decrement operator (++i or –i). The reasoning was that it was ugly. Now I agree that code should be somewhat nice looking, but not at the cost of performance. Here is the issue with pre- and post-increment operators:
The post-increment operator is supposed to return the original variable before the increment (or decrement). To do this, it is required to store that value somewhere, do the operation, store the operation, and then return the stored original value.
So what, you’re thinking. What’s the big deal? For the basic types, there is no big deal, and this will cause no real concern as the compiler is usually able to make this operation the same cost as for the pre-increment or decrement. But what if this is not a basic type? Obviously, in C this is no concern, but in C++, there are these wonderful things called classes. Classes have the ability to overload most operators, including the ++ and – operators pre- and post-. Classes also have constructors and destructors. In a post-increment (or decrement) a temporary instance of the type has to be created to store the original’s value, so if the type is a class, then it’s constructor is called, and when the increment is complete, it’s destructor is called. It is very conceivable to have a very expensive constructor and/or destructor.
If your code has to do the increment many times, i.e. in a big loop, then the delay could really add up. Unless you REALLY need the previous value, you should use the pre-increment operator to avoid this delay. I use it for the basic data-types as well, just so that I am in the habit of doing so. This makes it easier for me to remember to do it, but also, if I ever change a variable’s data-type, I don’t have to worry about changing every increment operator I use on it.