0

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?

long.luc
  • 1,191
  • 1
  • 10
  • 30
Amir
  • 73
  • 5
  • Why do you think hidden classes would be created here? You're setting all of your properties inside the constructor and only changing the values of the same (existing) properties. – mscdex Sep 09 '15 at 06:25
  • @mscdex: I think he is following this link: http://debuggable.com/posts/understanding-hidden-classes-in-v8:4c7e81e4-1330-4398-8bd2-761bcbdd56cb – long.luc Sep 09 '15 at 07:00

1 Answers1

2

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.

long.luc
  • 1,191
  • 1
  • 10
  • 30
  • How is it possible that there is such a drastic change in performance – Amir Sep 10 '15 at 04:31
  • 1
    It has nothing to do with the hidden classes though - first of all V8 does *not* create hidden classes for each individual indexed property assignment (indexed properties are `0`, `1`, etc). Indexed properties are handled really different from named properties in the hidden class system. The performance difference you see is all due to *array pre-allocation*. The original post you are following @Amir was flawed in it's explanation of what is happening. Disregard what is written there. – Vyacheslav Egorov Sep 12 '15 at 09:17