13

I read Is there a performance difference between i++ and ++i in C?:

Is there a performance difference between i++ and ++i if the resulting value is not used?

What's the answer for JavaScript?

For example, which of the following is better?

  1. for (var i = 0; i < max; i++) { // code } 
  2. for (var i = 0; i < max; ++i) { // code } 
5
  • Not enough to matter to you. I tend to prefer the ++i notation unless it's explicitly wrong for the use case. Commented Sep 20, 2012 at 0:50
  • with any decent js engine it should be identical Commented Sep 20, 2012 at 0:50
  • i hear there's a jsperf.com but not sure how to use it. Commented Sep 20, 2012 at 0:51
  • Pretty sure this is trivial for real performance. Commented Sep 20, 2012 at 0:52
  • Duplicate of stackoverflow.com/questions/1546981/… Commented Jun 15, 2022 at 17:54

2 Answers 2

16

Here is an article about this topic: http://jsperf.com/i-vs-i/2

++i seems to be slightly faster (I tested it on firefox) and one reason, according to the article, is:

with i++, before you can increment i under the hood a new copy of i must be created. Using ++i you don't need that extra copy. i++ will return the current value before incrementing i. ++i returns the incremented version i.

Sign up to request clarification or add additional context in comments.

4 Comments

This is really more of a comment. An answer would explain how that link answers the question.
@jasper i was coming to that :)
it depends on your browser. ++i is slower in safari but faster in some browsers.
"under the hood a new copy of i must be created" - only if you use the result...
-5

No. There is no difference in execution time. The difference in the two code snippets is when i gets incremented.

for(i = 0; i < max; i++) { console.log(i); } 

This first example will yield the results: 0,1,2,3,...,max-1

for(i = 0; i < max; ++i) { console.log(i); } 

This second example will yield the results: 1,2,3,...,max

i++ increments the value after the operation. ++i increments the value before the operation.

There is no performance difference other than the one less iteration it will make on ++i because the increment is done before the first operation

12 Comments

I'm not sure why the down-vote. The JSPerf linked-to in jidma's answer shows that the two perform the same.
Agreed, well within 1% of each other. ++i shows to be 1% slower in Safari 6.x. A good example to explain the difference is var i = 0; alert(++i); vs var i = 0; alert(i++);
-1. Both codes print the same thing.
@KarolyHorvath i agree, in order to have different results it should be for(i = 0; i < max; ) console.log(++i) vs for(i = 0; i < max; ) console.log(i++)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.