Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JavaScript optimize this object?

Imagine we define a new object like this:

const foo = {number1: 1, number2: 2}

This should define a new "Hidden Class" with these two properties.

Now imagine I define a new class using ES6 class syntax.

class Numbers {
  constructor() {
    this.number1 = 1
    this.number2 = 2
  }
}

and I create a new object from it.

const bar = new Numbers()

Now the question: Is the "Hidden Class" of the bar going to be the same as the Hidden Class of foo?

Because what I imagine is going on is that the first definition will create a new "Hidden Class" with two properties but the second will create a new "Hidden Class" then it will create a new "Hidden Class" with one property and then create yet another "Hidden Class" with yet another property resulting in three "Hidden Classes" linked together.

Can somebody clarify that? If my assumptions are right then the new "ES6 class syntax" is indeed slower.

Based on the article: JavaScript engine fundamentals: Shapes and Inline Caches · Mathias Bynens

like image 541
ProNOOB Avatar asked Jun 22 '18 14:06

ProNOOB


1 Answers

Now the question: Is the "Hidden Class" of the bar going to be the same as the Hidden Class of foo?

No. foo will create a hidden class like this (pseudocode):

{ number1: Number, number2: Number }

The construction of bar however will create three hidden classes, at first an empty one:

{}

Then the first property will be assigned and it extends the existing hidden class:

 { number1: Number } -> {}

After the second assignment it will get extended again:

{ number2: Number } -> { number1: Number } -> {}

So actually the hidden class is not equal to the hidden class of foo as it is split up across multiple hidden classes extending each other.

If my assumptions are right then the new "ES6 class syntax" is indeed slower.

Probably. Object literals are really fast, class constructors are a bit slower. They are actually even slower than regular functions, but the V8 team is working on it. But even if there is a small performance difference, you probably won't notice it in a lot of cases.

Read on

like image 156
Jonas Wilms Avatar answered Sep 19 '22 13:09

Jonas Wilms