javascript - n = n +1 is faster than n++ or ++n, why? - Stack Overflow

admin2025-04-15  0

Check this test case:

n = n + 1;

is faster than

n++;

and

++n;

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

Check this test case: http://jsperf./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 ?

Share Improve this question edited Jul 15, 2013 at 12:39 holographic-principle 19.7k10 gold badges48 silver badges62 bronze badges asked Jan 12, 2013 at 8:44 wewerewebwewereweb 1991 silver badge10 bronze badges 8
  • 3 Unless your code is actually doing 50,000,000 of these operations per second, you are wasting your time worrying about this. – user1233508 Commented Jan 12, 2013 at 8:47
  • you wont see much difference over few iterations – exexzian Commented Jan 12, 2013 at 8:48
  • 3 @Downvoters I'd actually like to know the reason behind this out of interest, since the jsPerf seems intact. – Flash Commented Jan 12, 2013 at 8:49
  • @Andrew - That's not what the OP is asking. The question is whether to avoid -- and ++. – Oded Commented Jan 12, 2013 at 8:49
  • Andrew was right, my question in the body was different than the one in the title. I've edited the body to clarify. – wewereweb Commented Jan 12, 2013 at 9:18
 |  Show 3 more ments

2 Answers 2

Reset to default 5

The performance will differ by browser and puter.

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.

Check this test. Or here is another test.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744696410a261739.html

最新回复(0)