I am seeing some odd behavior in a jsperf test. Here is the setup:
var pro={};
pro._x=3;
var q=Object.create(pro);
q.x=3;
q.z={};
q.z.x=3;
Then I simply lookup each of the properties q.x
, q._x
, and q.z.x
.
The single lookup q.x
is faster than the prototype lookup q._x
as expected. But the double lookup q.z.x
is the fastest. I expected q.z.x
to be the slowest, especially when compared to q.x
.
q.z.x
is even faster than q.z
. What is going on here?
The thing that makes the deeper lookup be faster is the fact that the JavaScript engine is able to better optimise the code for performance, as it knows exactly what object it is receiving.
Unlike using
Object.create
, where the engine is unable to perform its regular optimisation cycle, using a plain old empty object to initialise thez
property of theq
object, basically allows the engine to allocate appropriate memory and index it accordingly.This piece of code
var q=Object.create(pro);
basically tells the JS engine: "Hey, you're getting an instance of anObject
but I don't have a clue what type it is. Could be an Array, Objec, RegExp, Date.", while this piece of code --q.z={};
says -- "Hey, you're getting anObject
object here! Make sure to put aside some memory in accordance to this datatype".