<script>
function f(){
var t=document.getElementById("t");
var g=t.asdfg;
var a=new Date().getTime();
for(var x=0;x<100000000;++x){
if(g===undefined);
//if(g);
}
var b=new Date().getTime();
alert(b-a);
}
</script>
<body onload="f();">
<input id="t"/>
</body>
in Firefox if(g)
is slower than if(g===undefined)
. I'm wondering does anyone know any good explanation why this is the case?
in Chrome if(g)
is faster than if(g===undefined)
. I'm wondering does anyone know any good explanation why this is the case?
I'm not arguing that we should use one over the other.. i'm just interested in the theory
Arguably different browsers have different implementations but any theory on any browser would be worthy of an answer
There is no keyword undefined
in javascript, it does not work like null
does.
When you use
if(g===undefined)
undefined
will be parsed as an identifier. Therefore, the interpreter must check for existance of the undefined
variable in the global (window) scope. This lookup takes some time.
IMHO, the more correct way to check for undefinedness is (though not necessarily faster)
if(typeof(g) === 'undefined')
On the other hand, the expression if(g)
is most likely implemented as an implicit cast to a boolean, which of course also takes some time.
So my guess is that these two different operations are not equally fast in the Firefox and Chrome engines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With