I'm trying to find out the most effecient way to create a new instance of an object.
When I started, I used something like this:
var Foo = function(a, b, c)
{
this.a = a;
this.b = b;
this.c = c;
}
Foo.prototype.func = function()
{
// Do stuff;
}
var bar = new Foo(1, 2, 3);
bar.func();
Afterwards I heard it be better to skip the prototype because the new prototypes would use up unneeded memory, getting something like this:
var Foo = function(a, b, c)
{
return {
a:a,
b:b,
c:c,
func:function()
{
// Do stuff;
}
}
}
var bar = Foo(1, 2, 3);
bar.func();
However, now I have the problem of creating the same func multiple times when invoking multiple instances of Foo... so how about...
var Foo = {
a:null,
b:null,
c:null,
func: function()
{
// Do stuff;
}
}
function newFoo(a, b, c)
{
var tmp = function(){};
var obj = new tmp();
obj.prototype = Foo;
obj.a = a;
obj.b = b;
obj.c = c;
return obj;
}
var bar = newFoo(1, 2, 3);
bar.func();
But now I got the prototype back...
I am looking for speed here, that is my main concern. The objects in question are not too complicated, mostly a bunch of attributes and functions. Objects can be created and destroyed in a quick pace (this is why speed is important)
Who knows that the most effecient method is for this?
Don't worry, the prototype is apparently what's fastest for creating an object. http://jsperf.com/object-creation-efficiency gives it as being 2% faster than creating a new object, at least on Google Chrome Canary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With