JavaScript engines optimize memory using object shapes to track what properties they have.

Problem

How can we reduce memory usage when dealing with N objects that have the same keys but different values.

Solution

We maintain the representation of created objects using shapes and pointers to them.

There is also Property information containing metadata about the shape. If you wonder what information is stored there, see API for Object.seal(), Object.freeze().

Source: JavaScript Engines: The Good Parts™ by Mathias Bynens & Benedikt Meurer
Source: JavaScript Engines: The Good Parts™ by Mathias Bynens & Benedikt Meurer

What about assigning new properties?

When objects are getting modified, JavaScript engines extend the existing shape by creating a new branch.

Source: JavaScript Engines: The Good Parts™ by Mathias Bynens & Benedikt Meurer
Source: JavaScript Engines: The Good Parts™ by Mathias Bynens & Benedikt Meurer

Conclusion

The way how we create JavaScript objects have impact on the runtime. Be good citizen and initialize your objects in one go. There is a lot going on under the hood when JavaScript is executed.

I highly recommend to watch the talk and look into JavaScript engine internals.

🫵 If you enjoyed this article you can join my newsletter to get dose of weekly craftsmanship
    Unsubscribe anytime.

    References

    Go watch the talk about JavaScript Engines: The Good Parts™ by Mathias Bynens & Benedikt Meurer.