Obj vs Array Constructor and Access

JavaScript performance comparison

Revision 4 of this test case created

Info

Curious about whether it's faster to store simple structures in an object or an array.

There are a lot of ways to consider the problem such as:

Whether to place values in at definition time ([1,2,3], {a:1, b:2, c:3}) or after (a[0]=1, a[1]=2,... , o.a = 1, o.b = 2,...).

Storing uniform values, like all numeric, versus mixed, like numbers and strings

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    TEST_SIZE = 100000;
    array_of_arrays = [];
    array_of_objs = [];
   
};
</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
Arrays with Floats
for (var i=0; i < TEST_SIZE; i++) {
    var a = Math.random();
    var b = Math.random();
    var c = Math.random();
    var d = 'text';
    array_of_arrays.push([a, b, c]);
}

for (var i=0; i < TEST_SIZE; i++) {
    var o = array_of_arrays.pop();
    var a = o[0];
    var b = o[1];
    var c = o[2];
}
pending…
Objects with Floats
for (var i=0; i < TEST_SIZE; i++) {
    var a = Math.random();
    var b = Math.random();
    var c = Math.random();
    var d = 'text';
    array_of_objs.push(
        { a: a, b: b, c: c });
}

for (var i=0; i < TEST_SIZE; i++) {
    var o = array_of_objs.pop();
    var a = o.a;
    var b = o.b;
    var c = o.c;
}
pending…
Mixed Arrays
for (var i=0; i < TEST_SIZE; i++) {
    var a = Math.random();
    var b = Math.random();
    var c = Math.random();
    var d = 'text';
    array_of_arrays.push([a, b, d]);
}

for (var i=0; i < TEST_SIZE; i++) {
    var o = array_of_arrays.pop();
    var a = o[0];
    var b = o[1];
    var c = o[2];
}
pending…
Mixed Objects
for (var i=0; i < TEST_SIZE; i++) {
    var a = Math.random();
    var b = Math.random();
    var c = Math.random();
    var d = 'text';
    array_of_objs.push(
        { a: a, b: b, c: d });
}

for (var i=0; i < TEST_SIZE; i++) {
    var o = array_of_objs.pop();
    var a = o.a;
    var b = o.b;
    var c = o.c;
}
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