Hi Folks,
I'm wondering about access times on object members. More precisely, I'm benchmarking access times on the window
object. I believe I can explain most behavior here on my own, but I'd feel better to hear some comments.
Usecase: Different access times on different propertys ?
I'm benchmarking on Firefox 3.6.8 (windows), the simple measuring code looks like:
var loop = 100000;
console.time('bench');
while(loop--){
if(window.JSON)
var foo = 0;
}
console.timeEnd('bench');
The first strange thing is, it makes a different which property I'm looking up. For instance, window.JSON
seems to be faster to access, than window.localStorage
. There are other propertys/methods which can get accessed even faster.
Since there is no specification or defination within in the the ECMA-262 Language Specification, which order keys must have in an object, I guess each browser vendor implements it's own logic in which order keys
are stored in memory.
Could this be an explanation for this behavior? Like, JSON
is one of the very first keys and location
is more at the end? (In my test environment at least)
--
Another thing I noticed is, that calling if(JSON)
is slightly faster than if(window.JSON)
. If we forget about that you always should do the second call because of possible reference errors, those calls should have the same access time. I'm aware of ECMAscripts behavior on nested member lookups
(A nested member will cause the Javascript engine to go through the object member resolution, each time a dot is encountered), so window.location.href
must be slower than location.href
, but in this case.. is there a difference between JSON
and window.JSON
?
To end this, the fastest way to know whether or not the window
object owns a specific property/method is to use the IN
operator. That is about 10 times faster for the above examples.