PDA

View Full Version : prototype in JS class templates



chump2877
Mar 9th, 2007, 10:26 AM
I've been working in JS OOP lately, and finding that I am confused about the optimal implementation of prototype in generic class templates...

I read that every time a "class template" object is created, a unique set of privileged and/or private methods are created for that object....After a while, all of these copies of methods cause extra browser overhead and could spawn browser memory leaks....To avoid this possibility, and to ensure optimal performance, one should add methods to a class template's prototype, so that there will only ever exist one copy of a given method, regardless of the number of objects created...

Assuming that the above is true, it seems like, if you don;t absolutely need a method to be "private" or "privileged", that you should by default add all class methods to the class prototype...This way you ensure optimal browser performance....the trade-off seems to be that methods in the prototype are public and therefore accessible outside of an object (even if they don't really need to be publicly accessible)...But browser performance seems to be the more important issue here...

Can someone clearly confirm/refute/clarify the above for me?

jkd
Mar 9th, 2007, 06:19 PM
After a while, all of these copies of methods cause extra browser overhead and could spawn browser memory leaks....

They are just throwing a boogeyman at you, though that doesn't change the fact that using the prototype is faster for large numbers of instances.

You have an object and invoke a method. First it looks at its own properties. Then it looks at its prototype's properties. And then upwards, along the prototype chain. So the prototype is one scope resolution higher (making it negligably slower than direct property resolution), but as the article said, you only defined it once.

If you have:



function MyConstructor(bla) {
this.method = function() {};
this.method2 = function() {};
}


Then every time you say new MyConstructor(bla), it executes the Javascript in the function, which involves recreating those same anonymous functions time and time again. This is obviously slower if you initializing tons of instances.

I iterate again though, "slower" is not really measurable in anything but a theoretical sense here, as it would be impossible to actually notice it. The real advantage of using prototypes is saving memory.

chump2877
Mar 10th, 2007, 02:19 AM
They are just throwing a boogeyman at you, though that doesn't change the fact that using the prototype is faster for large numbers of instances.

I think that pretty much sums it up for me then...If I know right off the bat that I'll likely be instantiating A LOT of objects, then I should definitely start deferring to prototype....otherwise, the drop in performance resulting from using private/privileged methods is negligible....

Thanks a lot for your response...