gpt4 book ai didi

javascript - 为什么 Javascript 的 "in"运算符始终比严格成员与未定义的比较慢?

转载 作者:行者123 更新时间:2023-11-28 09:13:46 25 4
gpt4 key购买 nike

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

本质上,为什么要检查 if ('bar' in foo) {}明显慢于if (foo.bar !== undefined) {}

最佳答案

foo.bar !== undefined 仅检查这两个值以查看它们是否匹配。

而 foo 中的 'bar' 则必须使用某种机制来循环遍历 foo 的属性来查看 bar 是否在其中.

这是来自 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.

关于javascript - 为什么 Javascript 的 "in"运算符始终比严格成员与未定义的比较慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15937558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com