简体   繁体   English

优化条件/ if块,从性能角度来看,什么是更好的选择?

[英]Optimizing conditionals/if blocks, what is preferable from a performance point of view?

I am writing a JS library, and there are two things that have been on my mind for quite some time though. 我正在写一个JS库,但是有两件事我已经想了很长时间了。

Consider an option: 考虑一个选项:

var option = { bool : true } ;

Now, imagine I do either 现在,想象我要么

if(option.bool) 

      or

if(option.bool === true) 

The first case, despite knowing for sure that it's either true or false , I imagine is the equivalent of: 第一种情况,尽管可以肯定地知道它是true还是false ,但我想等于:

var tmp = options.bool;
if ( tmp !== undefined && tmp !== null && ( tmp === true || tmp ... ) 

That means that to try the options.bool = true it has to check both undefined and not null, before testing for true. 这意味着要尝试options.bool = true ,必须先测试undefined和not null,然后再测试true。

Therefore the latter case should be more performant. 因此,后一种情况应更有效。 However, the latter case, takes a considerably more characters and will lead to a larger lib, if repeated many times. 但是,如果重复多次,后一种情况将占用更多的字符,并且会导致更大的lib。

But maybe my understanding is incorrect. 但是也许我的理解是不正确的。

Right now, even if I do: 现在,即使我这样做:

var bool = window.t ? true : false; 

if ( bool === true ) // I still have to check for true to 'have the optmimal version'?

Maybe the last case can be optimized by the compiler, but when it's a global option I imagine it's different? 也许最后一种情况可以由编译器优化,但是当我选择全局选项时,我想它会有所不同吗?

Please share with me your thoughts on this. 请与我分享您对此的想法。

The answer is simple. 答案很简单。 It's less about coding patterns and more about logic. 它与编码模式无关,而与逻辑有关。 In this scenario there are always 3 possibilities and you need to cater for each of them. 在这种情况下,总是存在3种可能性,您需要分别应对每种可能性。 Ie. 就是 1. TRUE 2. FALSE 3. undefined If the value is undefined then do you want it to fall under the true or false clause? 1.正确2.错误3.未定义如果该值未定义,那么您是否希望它属于true或false子句? OR should it be catered for differently? 还是应该以其他方式来满足?

Another important thing to remember is that if it is undefined then it will always execute the code in the false clause. 要记住的另一件重要事情是,如果未定义,它将始终执行false子句中的代码。 Is that what you want? 那是你要的吗?

If you know that the value will always be either true or false then I suggest that you still use the syntax == true as this is more readable. 如果您知道该值将始终为true或false,那么我建议您仍使用== true语法,因为它更易读。 Someone browsing over the code would know that you are looking for the boolean value and not testing if the field has been set. 浏览代码的人会知道您正在寻找布尔值,而不是在测试是否已设置该字段。

You have to think about these 3 cases every time you have a boolean in an if statement, so there is no 1 answer for you. 每次在if语句中有布尔值时,您都必须考虑这3种情况,因此没有1个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM