Longest Word Javascript

JavaScript performance comparison

Test case created by worldclassdev

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const sampleText = 'Top Shelf Web Development Training on Scotch'
  
  function longestWordForLoop(text) {
      let wordArray = text.split(' ')
      let maxLength = 0
      let result = ''
      for (let i = 0; i < wordArray.length; i++) {
          if (wordArray[i].length > maxLength) {
              maxLength = wordArray[i].length
              result = wordArray[i]
          }
      }
      return result
  }
  
  function longestWordReduce(text) {
      var result = text.split(' ').reduce((maxLengthWord, currentWord) => {
          if (currentWord.length > maxLengthWord.length) {
              return currentWord
          } else {
              return maxLengthWord
          }
      }, "")
      return result
  }
  
  function longestWordSort(text) {
  
      var sortedArray = text.split(' ')
                            .sort((wordA, wordB) => wordB.length - wordA.length)
  
      return sortedArray[0]
  }

};
</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
Using a For-loop
longestWordForLoop(sampleText)
pending…
Using .reduce()
longestWordReduce(sampleText)
pending…
Using .sort()
longestWordSort(sampleText)
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