fast-array-filter
JavaScript performance comparison
Info
This is an Array#filter implementation from a recent 140bytes code golf entry. It's faster than native Array#filter when iterating over large sparse arrays because it doesn't use the length property to calculate when it should stop iterating.
Preparation code
<script>
Array.prototype.filter2 = function(
a, //a function to test each value of the array against. Truthy values will be put into the new array and falsey values will be excluded from the new array
b, // placeholder
c, // placeholder
d, // placeholder
e // placeholder
) {
c = this; // cache the array
d = []; // array to hold the new values which match the expression
for (e in c) // for each value in the array,
~~e + '' == e && e >= 0 && // coerce the array position and if valid,
a.call(b, c[e], +e, c) && // pass the current value into the expression and if truthy,
d.push(c[e]); // add it to the new array
return d // give back the new array
};
Array.prototype.filter3 = function(truthtest) {
var results = [];
for (var index=0, length=this.length; index<length; index++) {
if (truthtest.call(this[index], index, this))
results.push(this[index])
}
return results;
}
Array.prototype.filter4 = function(truthtest) {
var results = [];
for (var key in this) {
var numericKey = key+0;
if (numericKey == numericKey && truthtest.call(this[numericKey], numericKey, this))
results.push(this[numericKey])
}
return results;
}
</script>
<script>
Benchmark.prototype.setup = function() {
var sparse_array = []
sparse_array[200] = 'a'
var dense_array = [];
for(var i=0; i<200; i++) {
dense_array[i] = String.fromCharCode(Math.round(Math.random() * 95 + 33))
}
function callback(v) {
return /\w+/.test(v);
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
native vs sparse array |
|
pending… |
custom vs sparse array |
|
pending… |
native vs dense array |
|
pending… |
custom vs dense array |
|
pending… |
filter3 vs sparse array |
|
pending… |
filter3 vs dense array |
|
pending… |
filter4 vs sparse array |
|
pending… |
filter4 vs dense array |
|
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:
- Revision 1: published by John-David Dalton
- Revision 2: published
- Revision 3: published
- Revision 4: published
- Revision 5: published
0 comments