本文介绍了优化条件/如果块,从性能的角度来看最好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个JS库,但是有一段时间在我脑海里有两件事情。



考虑一个选项:

  var option = {bool:true }; 

现在,假设我要做

<$ p if(option.bool)



if(option.bool === true)
真或假,我想是相当于:

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

这意味着在测试true之前,要尝试 options.bool = true ,它必须检查undefined和not null。 / p>

因此后者应该更高效,但后者的情况会更多,如果重复多次,会导致更大的lib。 >

但是,也许我的理解是不正确的。

现在,即使我做:

  var bool = window.t?true:false; 

if(bool === true)//我仍然需要检查对于真正的'有最佳版本'?​​

也许最后的情况可以被编译器优化,但是当它是一个全局选项时,我想它是不同的?

请与我分享您对此的看法。

解决方案

答案很简单。这不是关于编码模式,更多是关于逻辑。
在这种情况下,总有3种可能性,你需要迎合他们每个人。
ie。 1. TRUE 2. FALSE 3. undefined
如果该值未定义,那么是否希望它属于真或假条款?或者它应该是不同的?



另一个重要的事情要记住的是,如果它是未定义的,那么它将始终执行伪代码中的代码。这是你想要的吗?

如果你知道这个值永远是真或假,那么我建议你仍然使用语法== true,因为这是更多可读。有人浏览代码会知道你正在寻找布尔值,而不是测试,如果该字段已被设置。

你每次都要考虑这些情况你在if语句中有一个布尔值,所以你没有1个答案。


I am writing a JS library, and there are two things that have been on my mind for quite some time though.

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:

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.

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.

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.Ie. 1. TRUE 2. FALSE 3. undefinedIf the value is undefined then do you want it to fall under the true or false clause? 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. 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. 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.

这篇关于优化条件/如果块,从性能的角度来看最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:42