Profiling `if(x)` VS `if(x===undefined)`
<script>
function f(){
var t=document.get开发者_高级运维ElementById("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.
精彩评论