Longest Word Javascript
JavaScript performance comparison
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.
Test | Ops/sec | |
---|---|---|
Using a For-loop
|
|
pending… |
Using .reduce()
|
|
pending… |
Using .sort()
|
|
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.
- Revision 1: published worldclassdev
- Revision 2: published Jesús Eduardo Clemens Chong
- Revision 3: published
- Revision 4: published
- Revision 5: published
0 Comments