Jun 13, 2016

Javascript Prototypes For Performance

Without Prototype : Lots of memory per object
  • Each time when you create object from below vehicle function,
  • the line function(name){  this.name = name;  }  is alocated memory each time the object is created,
  • so there are multiple instances of same function.
function vehicle(){
    this.name = 'truck';
    this.set_name = function(name){ 
        this.name = name; 
    }
}
var taxi = new vehicle();
With Prototype : Less memory per object
  • Each time when you create object from below vehicle function, 
  • only once memory is allocated to function , 
  • so there is only one instance of same function .
function vehicle(){
    this.name = 'plane';
}
vehicle.prototype.set_name = function(name){
    this.name = name;
}
var bike = new vehicle();

Conclusion : 

  • Since with prototype there is only one instance of the function instead of a multiple instances for each object.
  • So using prototype will be Performance Hit

No comments :

Post a Comment