【发布时间】:2017-09-29 07:10:21
【问题描述】:
我突然想知道这两个例子是否相同。
// sampler pack one
const something = '5'
console.log(typeof something)
const thing = +(something)
console.log(typeof thing)
// sampler pack two
const something2 = '5'
console.log(typeof something2)
const thing2 = Number(something2)
console.log(typeof thing2)
我的问题的本质是我经常使用Number() 来确保某些字符串被解释为数字,那么一元加运算符在 JavaScript 引擎盖下是否相同?还是更快?还是它突出了任何特殊情况? (尤其是大数或特殊类型的数字?)
我刚刚在这里进行了这个测试,结果显示它们非常相似:
const unaryStart = performance.now()
const something2 = '5'
const thing2 = +(something2)
const unaryEnd = performance.now()
console.log((unaryEnd - unaryStart) + ' ms')
const numberStart = performance.now()
const something = '5'
const thing = Number(something)
const numberEnd = performance.now()
console.log((numberEnd - numberStart) + ' ms')
0.0049999999999954525 ms
0.0049999999999954525 ms
【问题讨论】:
-
似乎是特定于实现的。结果在 Chrome、IE 和 Microsoft Edge 上几乎相同,但 Number() 在 Firefox 上始终慢 9-10 倍。
-
边缘情况当然是
Number没有引用您期望的内置函数,因为有人覆盖了全局或在本地隐藏了它。操作员无法做到这一点。