Sparse arrays vs full arrays
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
var n, N, i, I, sparse = [],
full = [],
full2 = [];
N = 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") {
full[i] = sparse[i];
full2[i] = sparse[i];
} else {
full[i] = 0;
full2[i] = 100 + 200 * Math.random();
}
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test  Ops/sec  

Sparse array sum


pending… 
Full array sum


pending… 
Running sparse on full array


pending… 
Sum all elements on a full array without zeros


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.
 Revision 1: published Mattias Ernelli
 Revision 3: published
 Revision 6: published Jasmine
 Revision 7: published
 Revision 8: published Andreas Öman
 Revision 9: published
 Revision 10: published
 Revision 11: published
 Revision 12: published
 Revision 16: published Lee Byron
 Revision 19: published
 Revision 21: published
 Revision 22: published
 Revision 23: published
 Revision 24: published
 Revision 25: published Tom
 Revision 26: published Volodymyr Vadyak
 Revision 27: published Volodymyr Vadyak
 Revision 28: published
 Revision 29: published
 Revision 31: published
1 Comment
Mattias Ernelli (revision owner) commented : ∞
OK, thats it, Sparse arrays in JS is way slower than just processing all elements of the array. Even if less than 1% of the sparse array is populated.
I will remove all code supporting sparse arrays in my numjs library which I'm working on from time to time...