javascriptnode.jsv8libv8

How to optimize using v8 hidden classes optimization techniques?


I want to use hidden class concept for making my web app fast.

I tried the following code from a tutorial on using hidden class,but it still shows abrupt results.

var PROPERTIES = 10000000;

function O(size) {
  for (var i = 0; i < size; i++) {
    this[i] = null;
  }
}

var o = new O(PROPERTIES);

var start = +new Date;

for (var i = 0; i < PROPERTIES; i++) {
  o[i] = i;
}

console.log(+new Date - start);

Here is jsperf link for benchmarking

Is it correct or there is something wrong in my implementation?


Solution

  • I think you are misunderstand the concept of hidden classes.

    Basically, both implementations have create hidden classes. The difference is the 2nd implementation moves creating hidden classes to initialize state, so when assigning actual data, it is faster than 1st implementation.

    In jsfidde, the accessing properties time is difference

    var PROPERTIES = 10000000;
    
    var obj = {};
    
    var s = Date.now();
    
    for (var i = 0; i < PROPERTIES; i++) {
       obj[i] = i;
    }
    
    console.log(Date.now() - s);
    

    Slower

    var PROPERTIES = 10000000;
    
    var Class = function() {
        for (var i = 0; i < PROPERTIES; i++) {
            this[i] = null;
        }
    };
    
    var obj = new Class();
    
    var s = Date.now();
    
    for (var i = 0; i < PROPERTIES; i++) {
        obj[i] = i;
    }
    
    console.log(Date.now() - s);
    

    Faster

    But the total execution times are the same, as you can see in your jsperf.

    Understanding this helps we can optimize response time by pre-creating all hidden classes, so when handle request/logic, accessing properties can be faster.