V8 optimizations

by podlipensky

JavaScript

//create all properites of class instances inside of constructor and always in the same order
//this will allow to prevent internal classes creation
//for single Person class there will be three classes created "empty person", "person with first name" and "person with first and last names"
function Person(){
    this.firstName = "";
    this.lastName = "";
}

//prefer to have numeric values which could be represented as 31-signed integer in order to avoid boxing (32th bit is uses to distinct values from objects)

//don't pre-allocate large arrays

//don't rely on default values of array
a = new Array();
for (var b = 0; b < 10; b++) {
  a[0] |= b;  // Oh no!
}
//vs.
a = new Array();
a[0] = 0;
for (var b = 0; b < 10; b++) {
  a[0] |= b;  // Much better! 2x faster.
}

//prevent unnecessary boxing/unboxing when deal with array elements of different type
var a = new Array();
a[0] = 77;   // Allocates
a[1] = 88;
a[2] = 0.5;   // Allocates, converts
a[3] = true; // Allocates, converts
//vs
var a = [77, 88, 0.5, true]; //better way

//Monomorphic Better Than Polymorphic (Operations are monomorphic if the hidden class is always the same)
function add(x, y) {
  return x + y;
}

add(1, 2);      // + in add is monomorphic
add("a", "b");  // + in add becomes polymorphic