Search code examples
javascriptv8

How V8 handles this/dict?


From V8 presentations, I know that it optimizes constructions like this with tagging a type object:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

What happens in the case I return an object (JSON), without using this? Will V8 apply the same optimization?

function parse() {
  ...
  // Suppose error happened (some branch of logic):
  return {
    pos: i,
    message: 'ka-boom'
  };
  ...
  // Everything is OK:
  return {
    value: 42
  };
}

In the sample above, will V8 tag with types objects (so, member access have chance to be real fast) or leave as maps? Note different paths return different objects.


Solution

  • Object literals get same optimization for the properties that are introduced inside the literal (not outside).

    Constructed objects right now additionally get up to 8 properties that can be introduced outside without penalty. This means subclasses can call parent constructor without worry for up to 8 properties. However optional introduction of properties is still bad of course.

    However, if your object literals require functions or other immutable heavy-weight data, not using prototypes will cost you dearly.

    Also in these cases the object will not yet necessarily become a hash table but the properties will just be placed in an external array. This is slower than Java/C++-like objects which they are in fastest mode but not as slow as the slowest hash table mode.

    So there is 3 modes of storage: fast in-object (like C++/Java objects), fastish out-of-object (no example), slow hashtable (like PHP, Python, Ruby in their canonical implementations)