Sparse arrays vs full arrays (v16)

Revision 16 of this benchmark created by Lee Byron on


Setup

var n, N, i, I, sparse = [], sparse2 = [], sparse3 = [],
        full = [],
        full2 = [];
    
    N = 32;//16384;
    I = 8;
    
    for (i = 0; i < I; i++) {
      do {
        n = (N * Math.random()) | 0;
        if (n > (N - 1)) {
          n = N - 1;
        }
      } while (sparse[n]);
      sparse[n] = -100 + 200 * Math.random();
    }
    full.length = N;
    full2.length = N;
    for (i = 0; i < N; i++) {
      if (typeof sparse[i] === "number") {
        sparse2[i] = sparse[i];
        sparse3[i] = sparse[i];
        full[i] = sparse[i];
        full2[i] = sparse[i];
      } else {
        sparse2[i] = undefined;
        sparse3[i] = null;
        full[i] = 0;
        full2[i] = -100 + 200 * Math.random();
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Sparse array sum
var sum = 0;
sparse.forEach(function(v, i) {
  sum += v;
});
ready
Full array sum
var len = full.length;
var sum = 0;
for (i = 0; i < len; i++) {
  sum += full[i];
}
ready
Running sparse on full array
var sum = 0;
full.forEach(function(v, i) {
  sum += v;
});
ready
Sum all elements on a full array without zeros
var len = full2.length;
var sum = 0;
for (i = 0; i < len; i++) {
  sum += full2[i];
}
ready
for loop over sparse
var len = sparse.length;
var sum = 0;
var entry;
for (var i = 0; i < len; i++) {
  (entry = sparse[i]) && (sum += sparse[i]);
}
 
ready
for loop over faux-sparse
var len = sparse2.length;
var sum = 0;
var entry;
for (var i = 0; i < len; i++) {
  (entry = sparse2[i]) && (sum += sparse2[i]);
}
 
ready
for loop over faux-sparse (null)
var len = sparse3.length;
var sum = 0;
var entry;
for (var i = 0; i < len; i++) {
  (entry = sparse3[i]) && (sum += sparse3[i]);
}
 
ready
loop over full (with 0 check)
var len = full.length;
var sum = 0;
var entry;
for (var i = 0; i < len; i++) {
  (entry = full[i]) && (sum += full[i]);
}
 
ready

Revisions

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