Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is having a nested function inside a constructor memory inefficient? [duplicate]

In JavaScript, we have two ways of making a "class" and giving it public functions.

Method 1:

function MyClass() {
    var privateInstanceVariable = 'foo';
    this.myFunc = function() { alert(privateInstanceVariable ); }
}

Method 2:

function MyClass() { }

MyClass.prototype.myFunc = function() { 
    alert("I can't use private instance variables. :("); 
}

I've read numerous times people saying that using Method 2 is more efficient as all instances share the same copy of the function rather than each getting their own. Defining functions via the prototype has a huge disadvantage though - it makes it impossible to have private instance variables.

Even though, in theory, using Method 1 gives each instance of an object its own copy of the function (and thus uses way more memory, not to mention the time required for allocations) - is that what actually happens in practice? It seems like an optimization web browsers could easily make is to recognize this extremely common pattern, and actually have all instances of the object reference the same copy of functions defined via these "constructor functions". Then it could only give an instance its own copy of the function if it is explicitly changed later on.

Any insight - or, even better, real world experience - about performance differences between the two, would be extremely helpful.

like image 350
MgSam Avatar asked Aug 29 '12 14:08

MgSam


5 Answers

You may use this approach and it will allow you to use prototype and access instance variables.

var Person = (function () {
    function Person(age, name) {
        this.age = age;
        this.name = name;
    }

    Person.prototype.showDetails = function () {
        alert('Age: ' + this.age + ' Name: ' + this.name);
    };

    return Person; // This is not referencing `var Person` but the Person function

}()); // See Note1 below

Note1:

The parenthesis will call the function (self invoking function) and assign the result to the var Person.


Usage

var p1 = new Person(40, 'George');
var p2 = new Person(55, 'Jerry');
p1.showDetails();
p2.showDetails();
like image 108
CodingYoshi Avatar answered Oct 06 '22 00:10

CodingYoshi


See http://jsperf.com/prototype-vs-this

Declaring your methods via the prototype is faster, but whether or not this is relevant is debatable.

If you have a performance bottleneck in your app it is unlikely to be this, unless you happen to be instantiating 10000+ objects on every step of some arbitrary animation, for example.

If performance is a serious concern, and you'd like to micro-optimise, then I would suggest declaring via prototype. Otherwise, just use the pattern that makes most sense to you.

I'll add that, in JavaScript, there is a convention of prefixing properties that are intended to be seen as private with an underscore (e.g. _process()). Most developers will understand and avoid these properties, unless they're willing to forgo the social contract, but in that case you might as well not cater to them. What I mean to say is that: you probably don't really need true private variables...

like image 44
James Avatar answered Oct 06 '22 01:10

James


In the new version of Chrome, this.method is about 20% faster than prototype.method, but creating new object is still slower.

If you can reuse the object instead of always creating an new one, this can be 50% - 90% faster than creating new objects. Plus the benefit of no garbage collection, which is huge:

http://jsperf.com/prototype-vs-this/59

like image 40
Yongtao Wang Avatar answered Oct 06 '22 01:10

Yongtao Wang


It only makes a difference when you're creating lots of instances. Otherwise, the performance of calling the member function is exactly the same in both cases.

I've created a test case on jsperf to demonstrate this:

http://jsperf.com/prototype-vs-this/10

like image 31
typeracer Avatar answered Oct 06 '22 01:10

typeracer


You might not have considered this, but putting the method directly on the object is actually better in one way:

  1. Method invocations are very slightly faster (jsperf) since the prototype chain does not have to be consulted to resolve the method.

However, the speed difference is almost negligible. On top of that, putting a method on a prototype is better in two more impactful ways:

  1. Faster to create instances (jsperf)
  2. Uses less memory

Like James said, this difference can be important if you are instantiating thousands of instances of a class.

That said, I can certainly imagine a JavaScript engine that recognizes that the function you are attaching to each object does not change across instances and thus only keeps one copy of the function in memory, with all instance methods pointing to the shared function. In fact, it seems that Firefox is doing some special optimization like this but Chrome is not.


ASIDE:

You are right that it is impossible to access private instance variables from inside methods on prototypes. So I guess the question you must ask yourself is do you value being able to make instance variables truly private over utilizing inheritance and prototyping? I personally think that making variables truly private is not that important and would just use the underscore prefix (e.g., "this._myVar") to signify that although the variable is public, it should be considered to be private. That said, in ES6, there is apparently a way to have the both of both worlds!

like image 40
Niko Bellic Avatar answered Oct 05 '22 23:10

Niko Bellic