Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ufocoder/4426e0209fd95e57df54cf0acc68d30a to your computer and use it in GitHub Desktop.

Select an option

Save ufocoder/4426e0209fd95e57df54cf0acc68d30a to your computer and use it in GitHub Desktop.
Hidden classes in JavaScript and Inline Caching

Hidden classes in JavaScript and Inline Caching

Knowing how internals work is always a good. Pretty much for everything. Cars, trains, computers, you name it. It gives you an insight on what happens under the hood. You also act/react differently based on this knowledge.

As you might have guessed, it’s also true for web development. Knowledge of CSS transitions allows you to achieve better performance and not to use JavaScript in most cases. Knowledge of V8 internals allows you to write more performant JavaScript code. So let’s talk about V8 a little.

V8 is a JavaScript engine built by Google. Firefox built SpiderMonkey, Opera built Carakan and Microsoft built Chakra. One very important difference between V8 and other JavaScript engines is that V8 doesn’t generate any intermediate code. It compiles JavaScript to machine code at execution.

It’s rather hard to optimize a dynamically typed, prototype-based language, such as JavaScript. Objects can change their type during runtime and it happens implicitly. To track types of JavaScript object and variables, V8 introduced the concept of hidden classes. During runtime V8 creates hidden classes that get attached to each and every object to track its shape/layout. That allows to optimize the property access time.

Consider the example:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName  = lastName;
}

var ironMan        = new Person(“Tony”,  “Stark”);
var captainAmerica = new Person(“Steve”, “Rogers”);
captainAmerica.age = 87;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment