loop-vs-iterator-reduce

JavaScript performance comparison

Revision 5 of this test case created by Krzysztof Miemiec

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function reduce(
      initialValue,
      reducer,
      data,
    ) {
      let acc = initialValue
      let count = 0
      for ( const item of data ) {
        acc = reducer( acc, item, count )
      }
      return acc
  }
  
  function simpleReduce(
      initialValue,
      reducer,
      data,
    ) {
      let acc = initialValue
      let count = 0
      for (let i=0, l=data.length; i<l; i++) {
        acc = reducer( acc, data[i], count )
      }
      return acc
  }
  
  function longestWordLengthLoop( str ) {
    const words = str.split( /\W+/g )
    let longestLength = 0
    for ( const word of words ) {
      longestLength = Math.max( longestLength, word.length )
    }
    return longestLength
  }
  
  const longestWordLengthReducer = ( longestLength, word ) => {
    return Math.max( longestLength, word.length )
  }
  
  
  const longestWordLengthReduce = str => reduce( 
      0, 
      longestWordLengthReducer, 
      str.split( /\W+/g )
  )
  
  const longestWordLengthSimpleReduce = str => simpleReduce( 
      0, 
      longestWordLengthReducer, 
      str.split( /\W+/g )
  )
  
  const longestWordLengthSimpleLoop = str => {
    const words = str.split( /\W+/g )
    let longestLength = 0
    for (let i=0, l=words.length;i<l;i++) {
      longestLength = Math.max( longestLength, words[i].length )
    }
    return longestLength
  }
  
  const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac suscipit nulla, vel egestas ex. Praesent tellus odio, commodo sed vulputate eget, ultrices ut nulla. Vestibulum condimentum in tellus faucibus commodo. In sollicitudin at velit in euismod. Praesent fringilla mi massa, et interdum augue viverra ac. Donec in efficitur mauris. Suspendisse accumsan vehicula tortor in molestie. Cras a odio sit amet tortor molestie faucibus. Phasellus sem turpis, posuere ut ultrices ac, gravida ac nunc.';
  

};
</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
reduce
longestWordLengthReduce(text)
pending…
simple loop
longestWordLengthSimpleLoop(text)
pending…
simple reduce
longestWordLengthSimpleReduce(text)
pending…
loop
longestWordLengthLoop(text)
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.

0 Comments