Pre-increment or Post-increment?

In most of the programming languages, there are two operators that can be used to increment a value by 1:
Pre-increment (++i) --> Before assigning the value to the variable, the value is incremented by 1.
Post-increment (i++) --> After assigning the value to the variable, the value is incremented.

It looks like both the operators are doing the same thing i.e., incrementing the value by one. But, there is an optimization side also which needs to be considered while using them instead of using any of them randomly.

Let's try to understand it step-by-step:
Using pre-increment:
Step-I: Fetch the value stored at the memory.
Step-II: Add 1 to the value.
Step-III: Store the value to the memory.
Step-IV: Assign the value, if needed.

Using post-increment:
Step-I: Fetch the value stored at the memory.
Step-II: Make a temporary copy of the variable to retain the previous value.
Step-III: Now, add 1 to the value.
Step-IV: Store the value to the memory.
Step-V: Assign the value, if needed.

As a result, pre-increment is faster than post-increment because post-increment keeps a copy of the previous value where pre-increment directly adds 1 without copying the previous value.

Comments (1)