iterating-over-arrays-and-objects

JavaScript performance comparison

Revision 7 of this test case created by Comparison of storing key:value data in an object and an array

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var array = [],
        object = {},
        sample_key = "",
        sample_value = "";
   
    for (var i = 0; i < 5000; i++) {
      var key = Math.random().toString(36).substring(7);
      var value = Math.random().toString(36).substring(7);
   
      array.push([key, value]);
      object[key] = value;
   
      if (2500 === i) {
        sample_key = key;
        sample_value = value;
      }
    };
};
</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
Iterating over array
for (i = 0; i < array.length; i++) {
  var result;
  result = array[i][0] + array[i][1];
}
pending…
Iterating over object's properties
for(var prop in object) {
  var result;
  if (object.hasOwnProperty(prop)) {
    result = prop + object.prop;
  }
}
pending…
Iterating over array forEach
array.forEach(function(item) {
  var result;
  result = item[0] + item[1];
});
pending…
access to the value (object)
var value = object[sample_key];
pending…
access to the value (array)
for (i = 0; i < array.length; i++) {
  if(sample_key === array[i]) {
    var value = array[i][1];
    break;
  }
};
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