DEV Community

Discussion on: The difference between x++ and ++x

Collapse
 
awwsmm profile image
Andrew (he/him)

Additionally, there can be a performance difference between prefix and postfix in some languages. If it doesn't matter to you which one is used, prefix (++i) should be your default. Reference

Collapse
 
somedood profile image
Basti Ortiz • Edited

Someone should make a jsPerf for that. Although I doubt a significant performance difference, it is nonetheless interesting (and exciting) to see the results.

Collapse
 
fabioemsm profile image
Fábio Moreira

It may have, performance implications in some languages. Think of these operators as functions (functors, I believe) as for ++x you'd something like:
public int ++operator (int &x) {
x = x + 1;
return x;
}
And for x++ you have something like
public int operator++ (int &x) {
int tmp = x;
x = x + 1;
return tmp;
}

As you can see, from the second example above, there is one more instruction needed to store the previous value of x and then return it.
But I don't think there is a major impact unless you use it extensively, also todays compilers may or may not predict and optimize the end result.
PS: the examples above only work in languages that have the concept of functors (function operators) like C++ does.