Object or extend prototype

Posted on
  • Re below snippets, can anyone advise what is least expensive from a memory perspect. I have a habit of doing the former, since I thought I had read it saved memory (or at least was quicker??) but notice that many of the modules extend prototype. So which is better, this?

    var myObj = {
     myproperties: {},
     method1: function() {},
     method2:function(){}
    };
    

    or this?

    myObj = function(){
     this.properties = {};
    };
    myObj.prototype.method1 = function(){};
    myObj.prototype.method2 = function(){};
    
  • If you're writing a module?

    Generally I'd say:

    • Putting stuff straight into the actual object saves a (very small) amount of RAM, and is a bit faster.
    • But if you're going to have more than one object, you're best to use prototype to reduce duplication.

    Also doing:

    function x() {
      return {
       myproperties: {},
       method1: function() {},
       method2:function(){}
      };
    }
    

    Isn't great, as you've got a copy of the code in the function itself, plus a copy in the instantiated object -> prototypes can be better there too.

    Just to add, when minifying, anything that's exposed to the outside world (like stuff in the prototype) can't have its name changed, so uses up more memory.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Object or extend prototype

Posted by Avatar for Ollie @Ollie

Actions