Why is Javascript's “in” operator consistently slower than strict member comparison to undefined?

前端 未结 2 761
孤独总比滥情好
孤独总比滥情好 2020-12-29 09:34

See http://jsperf.com/in-vs-member-object-access

Essentially, why is checking if (\'bar\' in foo) {} significantly slower than if (foo.bar !== und

2条回答
  •  天涯浪人
    2020-12-29 09:50

    foo.bar !== undefined checks just those 2 values to see if they match.

    While 'bar' in foo will have to use some mechanism to loop through the properties of foo to see if bar is in it.

    Here is an interesting Read from Ecma-script

    The in operator

    The production RelationalExpression : RelationalExpression in ShiftExpression is evaluated as follows:
    1. Evaluate RelationalExpression.
    2. Call GetValue(Result(1)).
    3. Evaluate ShiftExpression.
    4. Call GetValue(Result(3)).
    5. If Result(4) is not an object, throw a TypeError exception.
    6. Call ToString(Result(2)).
    7. Call the [[HasProperty]] method of Result(4) with parameter Result(6).
    8. Return Result(7).

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

    The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:
    1. Evaluate EqualityExpression.
    2. Call GetValue(Result(1)).
    3. Evaluate RelationalExpression.
    4. Call GetValue(Result(3)).
    5. Perform the comparison Result(4) === Result(2). (See below.)
    6. If Result(5) is true, return false. Otherwise, return true.

提交回复
热议问题