zjmiller
zjmiller

Reputation: 2807

Why is for (var i = 100; i--;) {} so much slower (70%) than for (var i = 100; i-->0;) {} in Firefox?

Here's the test: http://jsperf.com/forloopspeed

As you can see, the difference is huge in Firefox, present to a much lesser extent in Safari, and absent in Chrome and Opera.

The analogous thing happens with while loops too: http://jsperf.com/whileloopspeed

Upvotes: 4

Views: 143

Answers (3)

Boris Zbarsky
Boris Zbarsky

Reputation: 35084

This looks like some issue specific to Jaegermonkey. If I run the test under Tracemonkey, the effect disappears.

Filed https://bugzilla.mozilla.org/show_bug.cgi?id=670493

Upvotes: 2

user113716
user113716

Reputation: 322592

I suppose the internal ToBoolean() that is performed on the result of the expression is a bit slower when being given a number as compared to being given a boolean.

In this test I get a difference in performance when converting to boolean from a boolean vs a number using !!.

Upvotes: 2

Cristian Sanchez
Cristian Sanchez

Reputation: 32157

My guess is that checking whether i (a Number) is a falsy value is more computationally expensive than checking true/false (the result of the comparison).

Upvotes: 2

Related Questions