Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance difference between i++ and ++i in JavaScript? [closed]

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
}
like image 302
Oriol Avatar asked Sep 20 '12 00:09

Oriol


People also ask

Which is faster == or === in JS?

So === faster than == in Javascript === compares if the values and the types are the same. == compares if the values are the same, but it also does type conversions in the comparison. Those type conversions make == slower than ===.

Why === is faster than ==?

Equality operator == converts the data type temporarily to see if its value is equal to the other operand, whereas === (the identity operator) doesn't need to do any type casting and thus less work is done, which makes it faster than ==.

Is ++ i faster than i ++ Javascript?

Though we can say that the ++i is slightly faster than i++. The i++ takes local copy of the value of i before incrementing, while ++i never does. Sometimes some compiler optimizes the code if possible.


1 Answers

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.

like image 113
Majid Laissi Avatar answered Oct 17 '22 06:10

Majid Laissi