0

I know, in c++, ++i is better then i++.

++i;  // Fetch i, increment it, and return it  
i++;  // Fetch i, copy it, increment i, return copy

Here's same question about c++.

So, what about javascript ?

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
CALL ME TZ
  • 209
  • 1
  • 4
  • 10
  • 5
    Same semantics as C++. (Also it's a little weird to say that pre-increment is "better" than post-increment. It's *different*, but I don't see why it'd be better.) – Pointy Jan 07 '14 at 01:42
  • Define "better". Performance? If so, forget it. I don't believe you'll be able to enjoy the benefit (if any) of that level of optimization in JS. – cookie monster Jan 07 '14 at 01:43
  • [Tested](http://jsperf.com/prefix-or-postfix-increment) the performance on my iPhone and they are almost the same. – Mr. Polywhirl Jan 07 '14 at 01:46

2 Answers2

1

Taken from Guffa:

The difference between i++ and ++i is the value of the expression.

'The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment.

Example:

var i = 42;
alert(i++); // shows 42
alert(i); // shows 43
i = 42;
alert(++i); // shows 43
alert(i); // shows 43

The i-- and --i operators works the same way.'

So basically, the only difference is the result of the increment.

Cilan
  • 13,101
  • 3
  • 34
  • 51
0

Unless you're using the result of the increment, either in an assignment or as part of an expression, there's absolutely no difference between pre- and post-increment.

If you're using the result, pre-increment may be slightly faster because it doesn't need to save the old value while it's incrementing. But if you're using the result, you need to choose which form to use based on which value you need to assign -- you can't usually make the decision based on performance.

Barmar
  • 741,623
  • 53
  • 500
  • 612