All Articles

Hidden Classes in v8

If you are coming from language that has strong type like Java, C++ to Javascript you might be amazed by the way we can use Javascript Objects. In strongly typed languages when you are creating objects you will know all of the properties that the object will contain ahed of time. But in Js you can add whatever property you want later. so you could do

  let blog = {
    'title': 'Hello World',
    'views': 100
  };

  blog.description = 'First blog';

So the question now is how does Javascript handle this. Most strongly typed languages use some kind of some kind of map to represent this internally. But this would be really inefficient in dynamic language like Javascript, since Javascript engine does not know in advance the

V8 uses something called Hidden Classes to solve this.

Lets say there is a functions

function Blog(post, date){
  this.post = post;
  this.date = date;
}

const MyBlog = new Blog('First Blog', '2019-01-01');

When this code runs first during function declaration Javascript creates a empty hidden class.

Empty Hidden Class

Then when the code this.post is executed hidden second hidden class is created and the first hidden class now contains class transition to second hidden class.

Second Hidden Class

When the code this.date is executed the third hidden class is created with offset and the second hidden class contains class transition to third hidden class.

Third Hidden Class

Inline caching

The above optimization speeds up Javascript Objects while still keeping its dynamic nature. V8 has one more trick up its sleeve to speed up the code. Lets say we have have an object with method as given below

User.prototype.toString = function () {
  return this.displayName;
}

function sayHello(user){
  console.log(`Hello ${user.toString()}`);
}

when the above code is called with user object for the first two times

sayHello(user1);
sayHello(user2);

Javascript performs a dynamic lookup of the object type. But after first two times it caches it and V8 makes assumptions and skips the lookup and calls the toString() method directly speeding up the code more. So as long as you call the same object type again on the same function the code executes faster.

Take aways

  • When you add properties in different order it creates different hidden classes
  • Calling the same method multiple times is faster than calling different methods once (Meaning the more dry your code is more faster it is)