Testing Spread vs Mutable in Reduce (v2)

Revision 2 of this benchmark created on


Setup

const ARRAY = Array.from(new Array(10000)).map((el, i) => i)

const FILTER_FN = (num) => num % 2 == 0

Test runner

Ready to run.

Testing in
TestOps/sec
With spread operator
function splitArray (arr, filterFn) {

  return arr.reduce((acc, el) => {

    const conditionMet = filterFn(el)

    if (conditionMet)
      return { ...acc, filtered: [...acc.filtered, el] }

    return { ...acc, unfiltered: [...acc.unfiltered, el] }

  }, { filtered: [], unfiltered: [] })
}

splitArray(ARRAY, FILTER_FN)

ready
With mutable array
function splitArray (arr, filterFn) {

  return arr.reduce((acc, el) => {

    const conditionMet = filterFn(el)

    if (conditionMet)
      acc.filtered.push(el)
    else
      acc.unfiltered.push(el)

    return acc

  }, { filtered: [], unfiltered: [] })
}

splitArray(ARRAY, FILTER_FN)
ready
With concat
function splitArray (arr, filterFn) {

  return arr.reduce((acc, el) => {

    const conditionMet = filterFn(el)

    if (conditionMet)
      return { ...acc, filtered: acc.filtered.concat(el) }

    return { ...acc, unfiltered: acc.unfiltered.concat(el) }

  }, { filtered: [], unfiltered: [] })
}

splitArray(ARRAY, FILTER_FN)
ready

Revisions

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