gpt4 book ai didi

javascript - Object.is(x,y) 是否比其他比较更快?

转载 作者:行者123 更新时间:2023-11-29 10:56:05 24 4
gpt4 key购买 nike

所以在 JavaScript 中我们有三个相等比较运算符。我一直在阅读 ECMAScript 规范并了解它们的工作原理。有件事打动了我。 Object.is() 内置函数的比较步骤更少,并且比其他运算符更有可能提前终止。那么这是否会使 Object.is() 比其他运算符运行得更快?

以下是规范片段:

Object.is()

  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Number, then

    a. If x is NaN and y is NaN, return true.

    b. If x is +0 and y is -0, return false.

    c. If x is -0 and y is +0, return false.

    d. If x is the same Number value as y, return true.

    e. Return false.

  3. Return SameValueNonNumber(x, y).

松散等于==

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then

    a. Return the result of performing Strict Equality Comparison x === y.

  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

严格等于===

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is different from Type(y), return false.

  2. If Type(x) is Number, then

    a. If x is NaN, return false.

    b. If y is NaN, return false.

    c. If x is the same Number value as y, return true.

    d. If x is +0 and y is -0, return true.

    e. If x is -0 and y is +0, return true.

    f. Return false.

  3. Return SameValueNonNumber(x, y).

如果从事 JavaScript 编译器工作的人可以回答这个问题,那就太好了!

最佳答案

规范中的步骤越少并不一定意味着实现中的步骤越少。各种优化都适用于此。所以最后,我们所能做的就是实际 race the horses! (在您的现实世界用例中,一些合成 while(true) Object.is(1, 1); 不会生成任何有用的结果)。如果它真的(特别是)更快,它是否会使您的代码更好,例如是

      Object.is(user.age, 3)

更清楚
      user.age === 3

?

关于javascript - Object.is(x,y) 是否比其他比较更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56982781/

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