6

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

ProNOOB
  • 504
  • 2
  • 14
  • 3
    Nope he's talking about JS engine optimisations. โ€“ Ryan Searle Jun 22 '18 at 15:01
  • my understanding of es2015's classes were there were essentially syntactic sugar over the prototype chain, and my impression was they would compile to comparable objects. I'd be fascinated to hear the answer from someone more educated on the matter though. โ€“ dgeare Jun 22 '18 at 15:09
  • 1
    Some random guesses: `foo` and `Numbers` will have different hidden classes as their prototype is different. Additionally i guess that the constructor will be heavily optimized, causing it to only use one hidden class in the end, therefore classes are not slower at all compared to constructor functions and the difference to object literals is very small. โ€“ Jonas Wilms Jun 22 '18 at 15:11

1 Answers1

4

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

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151