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

I am trying to find the most efficient 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();

Subsequently, I heard that it is better to skip the prototype, because the new prototypes will use unnecessary 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 several times when calling 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, this is my main concern. The objects in question are not too complex, mostly a bunch of attributes and functions. Objects can be created and destroyed at a fast pace (which is why speed is important)

Who knows what is the most effective method for this?

+5
1

, , -, . http://jsperf.com/object-creation-efficiency 2% , , , Google Chrome Canary.

,

  • Chrome Canary 19.0.1056.0
  • Firefox 10.0.2

,

  • Chrome 17.0.963
+2

All Articles