Skip to content

Instantly share code, notes, and snippets.

@normanzb
Last active December 10, 2015 23:08
Show Gist options
  • Select an option

  • Save normanzb/4507630 to your computer and use it in GitHub Desktop.

Select an option

Save normanzb/4507630 to your computer and use it in GitHub Desktop.
Putting methods on prototype always memory efficient? No, use case should be considered carefully when design.
rubbish = [];
// Method 1, Suppose be memory efficient
// because we reuse the 2 function instance on the prototype chain
var MethodOnProto = function(){
};
MethodOnProto.prototype.method1 = function(){
this.method2();
};
MethodOnProto.prototype.method2 = function(){
console.log('sdfsdf');
};
// Method 2, Suppose to be memory consuming
// because we always create new function instance althought
// the function does the same thing
var MethodOnCtor = function(){
var me = this;
this.method1 = function(){
me.method2();
};
this.method2 = function(){
console.log('sdfsdf');
}
};
// However, think about this:
// 1) What if it is singleton? then theoretically the default memory taken should be the same.
// 2) What if the 2 methods are ususally used as async callback?:
var mop = new MethodOnProto;
var moc = new MethodOnCtor;
var defer = when.defer();
// when hooking up moc method, its quite straight forward:
defer.than(moc.method1);
// when hooking up mop method, you will have to create
// ANOTHER function to wrap around the original function
// to make sure the context is correct.
defer.then(mop.method1.bind(mop))
// image if you have quite a lot of places that do this?
@HuangKail
Copy link
Copy Markdown

your case does not show the reason choosing constructor way over prototype.
you can still gain the benefits from prototype by

var MethodOnCtor = function(){
var me = this;
this.method1 = function(){
me.method2();
};
};
MethodOnCtor.prototype.method2 = function(){
//xxx
};

in your defer case.

@normanzb
Copy link
Copy Markdown
Author

@HuangKail, i know, your method is actually almost the same as MethodOnCtor. you didn't get what i mean. I mean i suppose to be memory efficient so i just put the methods on prototype so that every time it gets 'new'ed it doesn't create 2 more function instances, but in some use case, it cause opposite result because the other will create the function that wraps context at the time they use it, so it actually consumes more memory.
#2 (and your method) theoretically cause more memory usage but in some in case, for example, singleton, or methods are more likely to be used as callback, it actually more memory efficient

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment