DEV Community 👩‍💻👨‍💻

Eugene Karataev
Eugene Karataev

Posted on

With great prototype power comes great responsibility

Let's say we have a simple object in JavaScript.

let obj = {a: 1};
console.log(obj.a);
Enter fullscreen mode Exit fullscreen mode

Accessing an object's property have O(1) complexity, i.e. it's super fast. But it's not that simple. If a property is not found, it's searched in the object's prototype. If it's not found again, the process continues until the prototype chain root is reached.

So, the property lookup process might be very time consuming in case of an object with long prototype chain.

Here's an example

function getObjectWithLongPrototypeChain(depth = 1) {
  let nextObj = {a: 1};

  for (let i = 0; i < depth; i++) {
    nextObj = Object.create(nextObj);
  }
  return nextObj;
}

let regularObject = {a: 1};
let longObject = getObjectWithLongPrototypeChain(1000000);

let t0;
let t1;
t0 = performance.now();
console.log(regularObject.a);
t1 = performance.now();
console.log(`Property lookup in the regular object took ${(t1 - t0)} milliseconds.`);

t0 = performance.now();
console.log(longObject.a);
t1 = performance.now();
console.log(`Property lookup in the object with long prototype chain took ${(t1 - t0)} milliseconds.`);

Enter fullscreen mode Exit fullscreen mode

And the results are

Property lookup in the regular object took 0.21500000730156898 milliseconds.
Property lookup in the object with long prototype chain took 42.249999998603016 milliseconds.
Enter fullscreen mode Exit fullscreen mode

So, the basic operation of property lookup for the second object took an incredible amount of time! While it's almost impossible to have objects with so long prototype chains in production code, I think it's good to know how JS engine resolves property lookup for objects.

Top comments (3)

Collapse
 
budyk profile image
Budy

let Object.prototype.hasOwnProperty() to the rescue

if (obj.hasOwnProperty('a')) {

}
Collapse
 
karataev profile image
Eugene Karataev Author

Yeah, thanks for mentioning this method. But using hasOwnProperty will console.log different result in the post's example, so use it with caution.

Collapse
 
miledi_delafer profile image
Anastasia

It's a great example of How JS works. Of course, nobody uses somethings as this longObject

But it makes sense to remember how it dangerous.

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!