Skip to content

Trivial JavaScript: (a || b) vs (a && b)

samholmes.me
1 pointsamholmes1 comment
On HN

Comments

I couldn't understand how !a&&!b would be slower; the NOT should be included in the branch.

The Firefox JIT inspector suggested that the body of the loop was being entirely removed, which makes sense, because it doesn't do anything. A body more like this does the trick:

    if(!a&&!b) {tt+=1;} else {tf+=1;}
You'll need to add the relevant declarations to the setup section.
    var tt=0,tf=0;
(The assignment to a and b should probably go there, too - it's in the teardown section at the moment.)

The result, though, is still the same!

I fixed this by switching the bodies round, so that !a&&!b runs first, then !(a||b) runs second. Now !a&&!b is quicker, as it should be, and I feel vindicated. Sort of.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.