Search code examples
javascriptinitializationlibrariesprototype-programmingpublic-method

Defining all public methods or prototype individual methods?


So when I make a library, I usually do it in this fashion:

var myLib = (function() {
    return {
        publicProperty: 'test',
        publicMethod: function() {
            console.log('public function');
        },
        anotherMethod: function() { //... },
        // .. many more public methods
    };
}());

I had overheard that creating libraries is faster and/or uses less memory for initialization if you write it like this:

var MyLib = function() {
   this.publicProperty = 'test';
};

MyLib.prototype = {
    publicMethod: function() {
        console.log('public method');
    },
    anotherMethod: function() { //... },
    // ... many more public methods
};

myLib = new MyLib();

Does one initialize faster than the other? Does my question even make sense? I assume that these accomplish the same task (that task being I go and use myLib.publicMethod() somewhere else in my code on docready). Thanks!


Solution

  • The two scripts produce different results.

    In the first you create the object myLib with three (or more) properties. Its prototype is Object.prototype. The point is you have made one object.

    In the second you create a global variable called publicProperty. This is probably not what you wanted. (EDIT: OP Question Corrected, this is no longer an issue.)

    Still, assuming you meant to create an object with methods in the prototype, your code is probably slower on a naive JavaScript engine because calling methods in the prototype requires a traversal of the link from the object to the prototype.

    Now if your intent is not to make a single but to make many instances of myLib then you will save a lot of memory by putting methods in the prototype, because you will have one copy of each function. You don't want thousands of copies of methods. :)

    EDIT TO ADDRESS OP QUESTION:

    Regarding the two approaches and how to make the first one "faster":

    Theoretically you have a space-time tradeoff. By putting the methods directly in the object you don't have the prototype chain lookup. But the downside is that every instance has its own copy of the methods. If you are making multiple instances, you should define each of the methods once and place them in a prototype. Modern (V8-class) JavaScript engines are pretty good with this kind of stuff, so you should not be looking for optimize speed by packing methods into the object. Now, for singletons, go ahead and fill up the object. Another approach is to put all the methods in myLib itself, and create instances with Object.create(myLib). This makes myLib itself be the prototype for all the "instances" and is generally considered good form (at least if you follow the "Good Parts" suggestions, which I generally do).