Array Performance (v27)

Revision 27 of this benchmark created on


Description

Manual array lookups vs. holey arrays.

Setup

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'});

Test runner

Ready to run.

Testing in
TestOps/sec
Manual Array Lookup
var id = 199;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
 
ready
Holey Array by Index
var id = '199';
var result = a2[id];
ready
Object by Key
var id = '199';
var result = o[id];
 
ready
Super-lucky
var id = 0;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
ready
Not quite so lucky.
var id = 100;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
ready
20
var id = 20;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
ready
40
var id = 40;
for (var i = 0; i < a1.length; i++) {
  if (a1[i].id == id) {
    result = a1[i];
    break;
  }
}
ready
Big string
var id = lastUUID;
for (var i = 0; i < s.length; i++) {
  if (s[i].id == id) {
    result = s[i];
    break;
  }
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.