3

My question is a follow-up to this one: Clearing up the `hidden classes` concept of V8

Suppose I have the following JavaScript code:

var values1 = [ 1, 2, 3, 4];
var values2 = [ 5, 6, 7, 8];
var fields = [ "f1", "f2", "f3", "f4" ];

function Construct (fields, values) {
   var i;
   for (i = fields.length - 1; i >= 0; --i) this [fields [i]] = values [i];
}

var a = new Construct (fields, values1);
var b = new Construct (fields, values2);

Then, will a and b end up having the same hidden class?

The background of this question is that, to me, this seems the only possibility to make use of the "hidden class" optimization if the property names are not known at programming time.

Practical relevance: Suppose you write an application dealing with tabular data where the names of the columns are dynamic (not known at programming time). Then the rows of the table semantically share the same class, yet if the engine does not optimize, you will better use an array and do the "column name -> index" conversion manually in your code (which may make the code ugly, as you have to cache indices).

Community
  • 1
  • 1
JohnB
  • 13,315
  • 4
  • 38
  • 65

1 Answers1

2

Yes. Hidden classes are a fully dynamic optimisation. In a first approximation, two objects will end up with the same class if (1) they are created by the same piece of code, and (2) they are added the same properties in the same order.

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72
  • Thank you! Well, are property accesses optimized as well? Say, does code like `var x = a [field];` somehow cache the value of `field` in order to make use of the hidden class feature and avoid property-name-to-offset translation when the statement is executed again? – JohnB Jun 02 '14 at 13:10
  • 1
    Yes, at least if the object is not in slow mode, `field` is a string, and has not changed too often. – Andreas Rossberg Jun 02 '14 at 13:45