Reputation: 973
I created this test http://jsperf.com/loop-counter why is there such a difference between these three expressions.
Upvotes: 7
Views: 640
Reputation: 49231
It's because of what the program is doing behind the scenes:
l_count += 1; This adds the number 1 to the variable.
l_count = l_count + 1; This calls the variable l_count, reads it, adds 1 to the result, and passes that back to l_count.
l_count++; This adds 1 to the variable after the line is run. So the value is stored in another temporary variable while the line is done, then the value is returned, added 1 and saved back to the original value.
Upvotes: 2
Reputation: 7503
because your test is wrong. you're reusing the same variable, so the larger it gets, the slower it is to increment. take a look at this: http://jsperf.com/loop-counter/6
this is how jsperf works - preparation code is run only once, before all tests.
Upvotes: 9
Reputation: 20333
If this is not a rhetorical question and you actually want an aswer then: becuse of how people have written the JS engine in the browsers.
Upvotes: 2
Reputation: 732
I tried running all three tests several times, and each time I reload the page, the first test I try is the fastest by far.
So I'm guessing there is some issue with the test being too short, i.e. the code that runs the tests is taking up most of the time.
Upvotes: 2