Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most efficient way to create a new instance of JS object

Tags:

javascript

oop

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?

like image 864
Johan Avatar asked Nov 05 '22 04:11

Johan


1 Answers

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.

Browsers where prototype is faster

  • Chrome Canary 19.0.1056.0
  • Firefox 10.0.2

Browsers where creating a new object is faster

  • Chrome 17.0.963
like image 172
Ry- Avatar answered Nov 10 '22 05:11

Ry-