Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the convertToFastObject function make it fast?

I tried Dart SDK after the 1.0 release, and wrote a simple hello-world program in Dart. Then, with the SDK tool, I generated the JavaScript file: helloworld.dart.js I went through the output js code, I saw there is a function named convertToFastObject. The definition is:

function convertToFastObject(properties) {
    function MyClass() {};
    MyClass.prototype = properties;
    new MyClass();
    return properties;
}

The usage code is like:

A = convertToFastObject(A);
B = convertToFastObject(B);

I know this code is for various kinds of Browsers, not for Chromium/Chrome only. I cannot understand, why the function can make the Object faster?

like image 844
mingjun Avatar asked Nov 20 '13 14:11

mingjun


1 Answers

This is a speed optimization for Google's V8 engine.

To be sure, this code snippet looks pretty weird: it assigns properties as the prototype of a constructor MyClass, then uses the constructor to build an instance with new MyClass(), and then returns properties. This is strange because 1) properties is never altered, and 2) the function never uses MyClass or the instance ever again.

Whenever you see strange behaviors like this, you can be fairly sure it's a speed optimization. In this case, the speed is gained by using V8's "hidden class" optimization. From a closely-related section of the Dart source:

// Use the newly created object as prototype. In Chrome,
// this creates a hidden class for the object and makes
// sure it is fast to access.

In the V8 engine, a constructed object is given a "hidden" C++ class to represent its set of properties. By constructing an object whose prototype is the properties object, the property values of properties become part of the new instance's C++ hidden class, which improves property-access speed.

I believe all objects in V8 have hidden classes by default, so the need for this technique isn't immediately obvious. However, it is possible for an object to lose its hidden class (and enter "slow mode" or "dictionary mode") by demonstrating that it doesn't benefit from the optimization. When an object deletes one of its properties or adds too many properties that are unrelated to the properties of any other objects, V8 assumes that a shared hidden class isn't valuable, because the object has no other similar object to share its hidden class with. This convertToFastObject function can re-instate a "slow mode" object's right to a hidden class by using it as the prototype of a newly constructed instance.

Related hidden class question, arising from a different Dart optimization: What is this generated code supposed (intended) to do?

like image 107
apsillers Avatar answered Sep 27 '22 20:09

apsillers