Compare finding longest words

Benchmark created on


Setup

const generateRandomWord = length => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
};

// Create an array of 10,000 random words with lengths between 1 and 15 characters
const words = Array.from({ length: 10000 }, () => generateRandomWord(Math.floor(Math.random() * 15) + 1));

Test runner

Ready to run.

Testing in
TestOps/sec
Caching lengths
let biggestIndex = 0, biggestWord = "", biggestLength = 0;

for (let i = 0, n = words.length; i < n; i++) {
  let word = words[i];
  let wordLength = word.length;
  
  if (wordLength > biggestLength) {
    biggestIndex = i;
    biggestWord = word;
    biggestLength = wordLength;
  }
}

ready
Looking up each iteration
let biggestIndex = 0;

for (let i = 0; i < words.length; i++) {
  if (words[i].length > words[biggestIndex].length) {
    biggestIndex = i;
  }
}
ready
Reduce
var biggestWord = words.reduce((accumulator, current) => {
  if (current.length > accumulator.length) {
    return current
  }
  return accumulator
}, "")
ready

Revisions

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