Performance on Javascript objects

6

Through what medium do you get the best performance of Javascript objects.

var Objeto = { 
    propriedade:'valorPropriedade',
    init:function() {
       //Inicia Objetos  
    }
}
var obj = Objeto.init();

or:

function Objeto() {
   this.propriedade = 'valorPropriedade';
   this.init = function(){
        //Função para iniciar o Objeto
   }
}

var obj = new Objeto();
obj.init();
    
asked by anonymous 27.02.2014 / 01:30

1 answer

5

The first choice for sure . When you create a constructor function and create an object through new , you are creating a prototype chain. That is, every object of type Objeto has a [[prototype]] property (not visible from JavaScript code, only indirectly via ), Which in this case is a common Object.getPrototypeOf(obj) fault (because you have not explicitly assigned Object ).

Objeto --> Object --> Object.prototype --> null

When you do not have a class Objeto.prototype , just a literal, its object is of the simple type Objeto , so this long string does not exist.

Object --> Object.prototype --> null

This reduces all the operations that JavaScript has to do on your object at 1 level. In practice, it should not make much difference, but if you want to squeeze every CPU cycle (I think it's silly, in my opinion, but it's your choice) then that option will be faster. Note: in the test that linkei above the performance is very different, but it is because the code does nothing useful. As the program grows, that gap must become smaller, or even negligible.

Update: As pointed out by @bfavaretto, the difference in performance is mainly due to the extra call of the constructor. If your code will do this frequently (create new objects) then the solution that does not use constructor should be faster. However, little can be said about the use of created objects in one way or another (at least, not from that test).

    
27.02.2014 / 02:13