Reduce vs for loop

JavaScript performance comparison

Test case created by GianlucaGuarini

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function assertOk(condition) {
    if (!condition) {
      throw new Error()
    }
  }
  
  function reduceClassicLoop(els) {
    const res = {}
  
    for(var i = 0; i < els.length; i++) 
      res[els[i]] = Symbol()
  
    return res
  }
  
  function reduceForOfLoop(els) {
    const res = {}
      
    for(const item of els) 
      res[item] = Symbol()
    
    return res
  }
  
  function simpleReduce(els) {
    return els.reduce((acc, el) =>{
      acc[el] = Symbol()
      return acc
    }, {})
  }
  
  function objectSpreadReduce(els) {
    return els.reduce((acc, el) => ({
      ...acc,
      [el]: Symbol()
    }), {})
  }

};
</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
classic for loop
const res1 = reduceClassicLoop(['uno', 'due'])

assertOk(typeof res1.uno == 'symbol')
assertOk(typeof res1.due == 'symbol')

const res2 = reduceClassicLoop(Array.from({ length: 100 }, (_, i) => i))

assertOk(typeof res2['1'] == 'symbol')
assertOk(typeof res2['99'] == 'symbol')
pending…
simple reduce
const res = simpleReduce(['uno', 'due'])

assertOk(typeof res.uno == 'symbol')
assertOk(typeof res.due == 'symbol')

const res2 = simpleReduce(Array.from({ length: 100 }, (_, i) => i))

assertOk(typeof res2['1'] == 'symbol')
assertOk(typeof res2['99'] == 'symbol')
pending…
reduce for of loop
const res = reduceForOfLoop(['uno', 'due'])

assertOk(typeof res.uno == 'symbol')
assertOk(typeof res.due == 'symbol')

const res2 = reduceForOfLoop(Array.from({ length: 100 }, (_, i) => i))

assertOk(typeof res2['1'] == 'symbol')
assertOk(typeof res2['99'] == 'symbol')
pending…
reduce using object spreading
const res = objectSpreadReduce(['uno', 'due'])

assertOk(typeof res.uno == 'symbol')
assertOk(typeof res.due == 'symbol')

const res2 = objectSpreadReduce(Array.from({ length: 100 }, (_, i) => i))

assertOk(typeof res2['1'] == 'symbol')
assertOk(typeof res2['99'] == 'symbol')
pending…

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

0 Comments