简体   繁体   English

在JavaScript中使用Double Equals是否会导致性能问题?

[英]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.

相关问题 双等于(==)和三等于(===)之间的JavaScript性能差异 - JavaScript performance difference between double equals (==) and triple equals (===) 多次调用javascript函数是否会导致任何不必要的问题? - Does calling a javascript function multiple time cause any unwanted issues? 将pushstate与内容重复使用是否会导致SEO问题? - Does using pushstate with content repeat cause SEO issues? 为什么 Javascript Array#shift 或 Array#slice 会导致性能问题? - Why Javascript Array#shift or Array#slice cause a performance issues? JavaScript中的循环性能问题 - Performance Issues with loops in JavaScript Javascript性能问题 - Javascript performance issues 服务器端的javascript函数在mongoDB中是否存在性能问题? - Does server-side javascript function have performance issues in mongoDB? 使用响应式设计时,一个视图上的多个D3js图形会导致性能问题 - Multiple D3js graphs on one view cause performance issues when using responsive disign JavaScript的双等于(==)总是对称的吗? - Is JavaScript's double equals (==) always symmetric? 使用大量jQuery调用来缩小页面上的JavaScript性能问题? - Narrowing down JavaScript performance issues on a page using a lot of jQuery calls?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM