Add a property to an array

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

<script>
  function plainArray() {
    var i = 0;
    var a = [];
    for (i = 0; i < 10000; i++) {
      a[i] = i;
    }
    var sum = 0;
    var l = a.length;
    for (i = 0; i < l; i++) {
      sum += a[i];
    }
    return sum;
  }

  function reservedArray() {
    var i = 0;
    var a = new Array(10000);
    for (i = 0; i < 10000; i++) {
      a[i] = i;
    }
    var sum = 0;
    var l = a.length;
    for (i = 0; i < l; i++) {
      sum += a[i];
    }
    return sum;
  }

  function reservedArrayWithProperty() {
    var i = 0;
    var a = new Array(10000);
    a.foo = 123;
    for (i = 0; i < 10000; i++) {
      a[i] = i;
    }
    var sum = 0;
    var l = a.length;
    for (i = 0; i < l; i++) {
      sum += a[i];
    }
    return sum;
  }

  function arrayWithProperty() {
    var i = 0;
    var a = [];
    a.foo = 123;
    for (i = 0; i < 10000; i++) {
      a[i] = i;
    }
    var sum = 0;
    var l = a.length;
    for (i = 0; i < l; i++) {
      sum += a[i];
    }
    return sum;
  }

  function objectWithProperty() {
    var i = 0;
    var a = {};
    a.foo = 123;
    for (i = 0; i < 10000; i++) {
      a[i] = i;
    }
    var sum = 0;
    var l = a.length;
    for (i = 0; i < l; i++) {
      sum += a[i];
    }
    return sum;
  }
</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
Plain array
plainArray();
pending…
Object used as array with property
objectWithProperty();
pending…
Initialized array
reservedArray();
pending…
Array with property
arrayWithProperty();
pending…
Initialized array with property
reservedArrayWithProperty();
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