[英]Does using the Double Equals in JavaScript Cause Performance Issues?
Per "strict mode" in JavaScript, you should use ===
when comparing values in an if-statement. 对于JavaScript中的“严格模式”,在if语句中比较值时应使用
===
。 However, when dealing with truthy/falsy values, this can lead to very long if-statements: 但是,在处理真实/虚假值时,这可能导致很长的if语句:
if (a !== null && a !== undefined && a !== '' && a !== 0) {}
To get around this, I've started using !!
为了解决这个问题,我开始使用
!!
if(!!a === true) {}
to cast the value as a boolean. 将值转换为布尔值。 However, I'm concerned there's a performance impact.
但是,我担心会影响性能。 According to my JSPerf ( http://jsperf.com/double-exclamation-vs-falsy/4 ), This approach is 30% slower than the long form of the if-statement.
根据我的JSPerf( http://jsperf.com/double-exclamation-vs-falsy/4 ),这种方法比if语句的长格式慢30%。
Am I way off base here? 我要离开这里吗? Has anyone else noticed a performance hit?
还有其他人注意到性能受到影响吗?
Using if(!!a) {
does have a significant performance hit because you're doing the same boolean conversion that JS does internally when you do if(a)
. 使用
if(!!a) {
确实会显着降低性能,因为执行if(a)
时,您将执行与JS内部相同的布尔转换。 It is more performant to do explicit type checking like if(a === true)
or if(a !== null && a !== undefined)
执行显式类型检查(如
if(a === true)
或if(a !== null && a !== undefined)
性能更高
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.