1

I created a performance test to compare array value search to object key lookup, and discovered that when doing key lookup when the key doesn't exist in the object is much slower than when the key exists. It's even slower than searching this value in an array.

This answer states that on Chrome, objects are implemented using classes, but I can't figure out why this makes the lookup slower.

Any ideas?

Community
  • 1
  • 1
Tzach
  • 12,889
  • 11
  • 68
  • 115

1 Answers1

3

When a key is not found the entire prototype chain will be traversed, looking for that key.

From ECMA-262 §4.2.1 Objects:

Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s "prototype" property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. When a reference is made to a property in an object, that reference is to the property of that name in the first object in the prototype chain that contains a property of that name. In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

figure 1 – object/prototype relationships

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Great answer! Is this documented somewhere? – Tzach Apr 16 '15 at 15:17
  • 1
    There are [roughly a bajillion articles online](https://www.google.com/search?q=javascript%20prototype%20chain) about the prototype chain lookup in JS. Take your pick. Outside of [the ECMA-262 specification](http://www.ecma-international.org/ecma-262/5.1/#sec-4.2.1), [Mozilla's](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) is probably the most authoritative. – Matt Ball Apr 16 '15 at 15:18