Obj vs Array Constructor and Access

JavaScript performance comparison

Test case created by Josh Pearce

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++) {
    array_of_arrays.push([Math.random(), Math.random(), Math.random()]);
}

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];
    /* trying to use the values in some way so the code is not
       optimized away by the JITC */

    //var sum = a + c;
}
pending…
Objects with Floats
for (var i=0; i < TEST_SIZE; i++) {
    array_of_objs.push(
        { a: Math.random(), b: Math.random(), c: Math.random() });
}

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;
    /* trying to use the values in some way so the code is not
       optimized away by the JITC */

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

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];
    /* trying to use the values in some way so the code is not
       optimized away by the JITC */

    //var sum = a + c;
}
pending…
Mixed Objects
for (var i=0; i < TEST_SIZE; i++) {
    array_of_objs.push(
        { a: Math.random(), b: 'text', c: Math.random() });
}

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;
    /* trying to use the values in some way so the code is not
       optimized away by the JITC */

    //var sum = a + 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