Searching algorithm
importance: 5
The task has two parts.
Given the following objects:
let head = {
glasses: 1
};
let table = {
pen: 3
};
let bed = {
sheet: 1,
pillow: 2
};
let pockets = {
money: 2000
};
- Use
__proto__
to assign prototypes in a way that any property lookup will follow the path:pockets
→bed
→table
→head
. For instance,pockets.pen
should be3
(found intable
), andbed.glasses
should be1
(found inhead
). - Answer the question: is it faster to get
glasses
aspockets.glasses
orhead.glasses
? Benchmark if needed.
-
Let’s add
__proto__
:let head = { glasses: 1 }; let table = { pen: 3, __proto__: head }; let bed = { sheet: 1, pillow: 2, __proto__: table }; let pockets = { money: 2000, __proto__: bed }; alert( pockets.pen ); // 3 alert( bed.glasses ); // 1 alert( table.money ); // undefined
-
In modern engines, performance-wise, there’s no difference whether we take a property from an object or its prototype. They remember where the property was found and reuse it in the next request.
For instance, for
pockets.glasses
they remember where they foundglasses
(inhead
), and next time will search right there. They are also smart enough to update internal caches if something changes, so that optimization is safe.