Array Performance

JavaScript performance comparison

Revision 27 of this test case created

Info

Manual array lookups vs. holey arrays.

Preparation code

<script>
  Benchmark.prototype.setup = function() {
    var generateUUID = (function () {
      var format = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
      var regex = /[xy]/g;
      var callback = function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      };
      return function () {
        return format.replace(regex, callback);
      };
    }());
   
    var a1 = [];
    for (var i = 0; i < 200; i++)
      a1.push({id: i, name: 'name1'});

    var a2 = [];
    a2[198] = {id: 199, name: 'name1'};
    a2[199] = {id: 199, name: 'name1'};

    var o = {};
    for (i = 0; i < 200; i++)
      o[i] = {id: i, name: 'name1'};
   
    var s = [];
    var lastUUID;
    for (i = 0; i < 200; i++)
      lastUUID = generateUUID();
      s.push({id: lastUUID, name: 'name1'});
  };
</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
Manual Array Lookup
var id = 199;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
 
pending…
Holey Array by Index
var id = '199';
var result = a2[id];
pending…
Object by Key
var id = '199';
var result = o[id];
 
pending…
Super-lucky
var id = 0;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
pending…
Not quite so lucky.
var id = 100;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
pending…
20
var id = 20;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
pending…
40
var id = 40;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
pending…
Big string
var id = lastUUID;
for (var i = 0; i < s.length; i++) {
  if (s[i].id == id) {
    result = s[i];
    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