Most efficient way to create an instance of an object

JavaScript performance comparison

Test case created by minitech

Info

Compares the speed of different options for creating an object.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var Foo = function(a, b, c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }
   
    Foo.prototype.func = function()
    {
        // Do stuff;
    }
   
    var Foo2 = function(a, b, c)
    {
        return {
            a:a,
            b:b,
            c:c,
            func:function()
            {
                // Do stuff;
            }
        }
    }
   
   
    var Foo3 = function(a, b, c) {
        var r = {};
   
        r['a'] = a;
        r['b'] = b;
        r['c'] = c;
        r['func'] = function() {
            // Do stuff
        };
   
        return r;
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Using the prototype
var bar = new Foo(1, 2, 3);
bar.func();
pending…
Creating a brand new object
var bar = Foo2(1, 2, 3);
bar.func();
pending…
Object first
var bar = Foo3(1, 2, 3);
bar.func();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment