# arr-map-filter-reduce

## JavaScript performance comparison

Test case created by G. Lathoud

## Preparation code

<script>
Benchmark.prototype.setup = function() {
var n = 10000,
arr = new Array(n)
drop = 0.1 // Proportion of numbers to drop
;

// Deterministic pseudo-random numbers to make sure
// arr is always generated the same way.
// http://stackoverflow.com/questions/521295/javascript-random-seeds
var seed = 1;

function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}

for (var i = n; i--;)
arr[i] = {
p: random() < drop ? null : i
};

};
</script>

## Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
3 loops
// .map(".p")
var tmp_1 = new Array(n);
for (var i = 0; i < n; i++)
tmp_1[i] = arr[i].p;

// .filter("!=null")
var tmp_2 = [];
for (var i = 0; i < n; i++) {
var v = tmp_1[i];
if (v != null)
tmp_2.push(v);
}

// .reduce("+")
var sum = 0;
for (var n2 = tmp_2.length, i = 0; i < n2; i++)
sum = sum + tmp_2[i];
pending…
1 loop
var sum = 0,
n = arr.length;
for (var i = 0; i < n; i++) {
var v = arr[i];
v = v.p;         // .map(".p")
if (v != null)   // .filter("!=null")
sum = sum + v; // .reduce("+")
}
pending…

## Revisions

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