Last Updated: February 25, 2016
·
1.352K
· vraa

Attaching JavaScript functions to prototype vs Object instances

Full article: http://veerasundar.com/blog/2014/02/javascript-prototype-methods-vs-object-methods/

When you attach methods to object instances, then each instance will have it's own copy of the method. This involves the system processing time and the memory.

But, when you attach the method to object's prototype, then only one version of the method exists. This doesn't need as much processing time and memory when compared to the above approach.

Let's see this with an example.

var Parent = function(){
  this.yellAtKid = function(){
    console.log('Somebody gonna get a hurt real bad!');
  };
};
console.profile('Object Methods');
var dads = [];
for(var i=0; i<=10000000; i++){
  dads.push(new Parent());
}
console.profileEnd(); // 4903.267ms

When I profiled the above code in Firefox / Mac, the populate() method took about 4903.267ms to execute. If I changed method attachment to prototype instead, like below:

var Parent = function(){
};

Parent.prototype.yellAtKid = function(){
  console.log('Somebody gonna get a hurt real bad!');
};

console.profile('Prototype Methods');
var dads = [];
for(var i=0; i<=10000000; i++){
  dads.push(new Parent());
}
console.profileEnd(); // 3271.413ms

This time, the populate() method took only 3271.413ms seconds. So, about 1.5 seconds we save, just by reattaching the methods to prototype.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside