Optimization of conventions / blocks, which is preferable in terms of performance?

I am writing a JS library, and there are two more things that have been in my head for quite some time.

Consider the option:

var option = { bool : true } ; 

Now imagine what I'm doing either

 if(option.bool) or if(option.bool === true) 

In the first case, despite the fact that he is sure that he is true or false , I think this is the equivalent:

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

This means that to test options.bool = true, it must check both undefined and non-null before testing true.

Therefore, the latter case should be more effective. However, the latter case takes significantly more characters and will lead to an increase in lib if repeated many times.

But maybe my understanding is wrong.

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 is a global parameter , I think it is different?

Please share with me your thoughts on this.

0
javascript firefox google-chrome
Sep 16 '15 at 17:54
source share
1 answer

The answer is simple. This is less about coding schemes and more about logic. There are always three possibilities in this scenario, and you need to service each of them. I.e. 1. TRUE 2. FALSE 3. undefined If the value is undefined, do you want it to fall under a true or false sentence? OR should it be served differently?

Another important thing to keep in mind is that if it is undefined, it will always execute code in a false sentence. Is this what you want?

If you know that the value will always be true or false, I suggest you use the syntax == true, as this is more readable. Someone looking at the code will know that you are looking for a boolean and not checking if the field is set.

You have to think about these three cases every time you have a boolean expression in an if statement, so there is no 1 answer for you.

0
Jan 15 '16 at 9:21
source share



All Articles