FilterMap vs Reduce vs For vs Function vs Method

JavaScript performance comparison

Test case created by cborchert

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const theArray = Array.apply(null, {length: 50}).map((entry, i)=>{
    return {value: 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
filter-map
const theNewArray = theArray
  .filter(({ value }) => value % 3 !== 0)
  .map(({ value }) => `my value is ${value}`);
pending…
reduce
const theNewArray = theArray.reduce(
  (acc, { value }) =>
    value % 3 === 0 ? [...acc, `my value is ${value}`] : acc,
  []
);
pending…
for
const theNewArray = [];
const theArrayLength = theArray.length;
for (let i = 0; i < theArrayLength; i++) {
  const value =  theArray[i].value;
  if (value % 3 === 0) theNewArray.push(`my value is ${value}`);
}
pending…
function
function filterMap(arr, filter, map) {
  const acc = [];
  for (let i = 0; i < arr.length; i++) {
    if (filter(arr[i])) acc.push(map(arr[i]));
  }
  return acc;
}
const theNewArray = filterMap(
  theArray,
  ({ value }) => value % 3 === 0,
  ({ value }) => `my value is ${value}`
);
pending…
method
Array.prototype.filterMap = function(filter, map) {
  const acc = [];
  for (let i = 0; i < this.length; i++) {
    if (filter(this[i])) acc.push(map(this[i]));
  }
  return acc;
}
const theNewArray = theArray.filterMap(
    ({ value }) => value % 3 === 0,
    ({ value }) => `my value is ${value}`
  );
pending…

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

Compare results of other browsers

0 Comments