\" grea" />
开发者

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

开发者 https://www.devze.com 2023-04-10 14:30 出处:网络
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 \">\" grea

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消