I’ve been told in the past by a programming mentor that ++x
is faster than x++
, and I found myself refactoring a few increments in javascript the other day.
But then I got thinking – is it really faster? Wouldn’t most modern compilers optimize out the difference? I decided to do some science.
Here’s an outline of the code I ran on JSPerf:
var x = 0; var obj = { x: 0 } // test one: x++; // test two: ++x; //test three: ++obj.x; //test four: obj.x++
Results:
For the most part, ++x
has the same microperformance as x++
.
Modern versions of Android Browser, Chrome, Firefox, Internet Explorer, and Safari all have similar performance for each of the benchmarks. This overrides my existing belief that prefix notation is faster.
In some browsers, there is a small but noticeable difference.
In FF19, ++x
is faster than x++
. But ++obj.x
and obj.x++
are the same speed.
In FF31, ++x
is faster than x++
, but obj.x++
is faster than ++obj.x
.
One interesting thing is that some browsers prefer x++
and others prefer ++x
. The largest difference, FF31, is around a 1% increase in performance. But, Chrome Mobile loses that same amount (~1%), preferring x++
over ++x
, so ultimately it’s a wash unless you’re targeting a specific browser.
From Manhattan,
–Erty
Leave a Reply