Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

n = n +1 is faster than n++ or ++n, why?

Check this test case: http://jsperf.com/n-n-1-or-n

n = n + 1;

is faster than

n++;

and

++n;

Any clue about why the first writing is so much faster on many browsers ?

like image 260
wewereweb Avatar asked Oct 20 '25 21:10

wewereweb


1 Answers

The performance will differ by browser and computer.

I see that n = n + 1 on my setup is about 4 times faster.

At the same time, the slowest is over 62 million ops per second.

You are micro-optimizing here. The usage of one over another is hardly going to be a bottleneck.


Why it is faster in some browsers? I don't know. You would need to dig into the source code of the different JavaScript engines to find out.

Chances are good that there is an optimization for this case due to how some popular micro-benchmarks are written.

like image 139
Oded Avatar answered Oct 22 '25 11:10

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!