简体   繁体   中英

Is '===' more efficient than '!=='?

Am i correct in saying that this:

if (y === x) {
    //statement a
} else {
    //statement b
}

is more efficient than this:

if (y !== x) {
    //statement b
} else {
    //statement a
}

Note: the order of statements.

First I'll say "no", or at least it can't be reliably decided since it'll always ultimately be implementation dependant.

Having said that, the !== has one additional step described in the specification, which is to return the opposite of the comparison result. Otherwise they're identical.

11.9.4 The Strict Equals Operator ( === )

The production EqualityExpression : EqualityExpression === RelationalExpression is evaluated as follows:

  1. Let lref be the result of evaluating EqualityExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating RelationalExpression.
  4. Let rval be GetValue(rref).
  5. Return the result of performing the strict equality comparison rval === lval. (See 11.9.6)

11.9.5 The Strict Does-not-equal Operator ( !== )

The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:

  1. Let lref be the result of evaluating EqualityExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating RelationalExpression.
  4. Let rval be GetValue(rref).
  5. Let r be the result of performing strict equality comparison rval === lval. (See 11.9.6)
  6. If r is true, return false. Otherwise, return true.

I'll let you decide if that step should be of concern, but again, this is just the language specification . Who knows what tricks the implementations do.

=== has to compare every single character of the two variables (if they have more than one), while !== can fail quite quickly if the first characters don't match. So !== should be a bit faster, but normally the benefits are so small that you won't notice them. I'd also recommend Pointy's way to look for the better logic.

No. They are very similar. I created a jsfiddle http://jsfiddle.net/rEtjn/

var date1,date2;
date1=new Date();
for(a=1;a<=10000;a++){
    if(i===a){
        console.log("hello!");
    }
    else{
        console.log("bye!");
    }
}
date2=new Date();
alert(date2-date1);
date1=new Date();
for(a=1;a<=10000;a++){
    if(i!==a){
        console.log("bye");
    }
    else{
        console.log("hi!");
    }
}
date2= new Date();
alert(date2-date1);

Both run within 10 milliseconds of each other most of the time. Do whatever you want, but they are the same speed.

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