一元运算符 +(variable) 的解释与 Number(variable) 相同吗?
Is unary operator +(variable) interpretted the same as Number(variable)?
我突然想知道这两个例子是不是一模一样。
// 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
两者都将字符串转换为 Number
,来自 MDN 关于 unary plus +
:
[...] unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.
来自标准 ECMA 262 V 6,unary plus:
UnaryExpression : + UnaryExpression
- Let expr be the result of evaluating UnaryExpression.
- Return ToNumber(GetValue(expr)).
从标准 ECMA 262 V 6 开始,Number 需要更多步骤,因为数字可以作为构造函数调用,并且在第 4 步中检查,这需要一些时间。
- If NewTarget is undefined, return n.
我突然想知道这两个例子是不是一模一样。
// 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
两者都将字符串转换为 Number
,来自 MDN 关于 unary plus +
:
[...] unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.
来自标准 ECMA 262 V 6,unary plus:
UnaryExpression : + UnaryExpression
- Let expr be the result of evaluating UnaryExpression.
- Return ToNumber(GetValue(expr)).
从标准 ECMA 262 V 6 开始,Number 需要更多步骤,因为数字可以作为构造函数调用,并且在第 4 步中检查,这需要一些时间。
- If NewTarget is undefined, return n.