Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-5
rated 0 times [  2] [ 7]  / answers: 1 / hits: 16808  / 12 Years ago, wed, august 29, 2012, 12:00:00

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.


More From » performance

 Answers
2

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...


[#83352] Tuesday, August 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mollys

Total Points: 183
Total Questions: 95
Total Answers: 85

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;