简体   繁体   中英

Is there a performance difference in JavaScript between “>” and “!=”?

Doing a bind for a previous link in a nav. If we're on the first position don't do the same thing for the previous link. I was doing a "!=" not equal to test, but realized it could be a ">" greater than.

Then I thought, is one faster?

if (numberToCheck != 0) {
    //doSomething();
}

vs.

if (numberToCheck > 0) {
    //doSomething();
}

Performance questions should be resolved via measurement, not speculation.

You can see for yourself here http://jsperf.com/inequality-vs-greater-than . The results of this test (on my computer) vary by browser. Some are faster with inequality. Some are faster with less than. You will likely find much bigger speed differences in other areas of your code.

If you want to test something slightly different than what I put in the test, just add your own test for comparison.

Do you mean like... absolute difference, or "meaningfully different"?

In any case, it would depend 100% on the underlying VM implementation. It might be faster to set a flag and have that flag be the first in an && (for short-circuiting), though, and have the numerical part second.

if (keepChecking && numberToCheck != 0) {
    keepChecking == false;
    // doSomething();
}

Again, VM-dependent, and I can't believe it'd matter a lot either way.

What about -

if (numberToCheck !== 0) {
//doSomething();
}

Actually, I doubt a human could notice the difference. Plus, each browser js engine might yield different results.

I made a test page at jsperf:

http://jsperf.com/different-from

In Chrome on my MacBook Pro, they are exactly the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM