DEV Community

Discussion on: Are one-liners always the best solutions?

Collapse
 
noclat profile image
Nicolas Torres • Edited

Indeed! For loop is a core syntax element of JavaScript so, if written decently, will always be faster than iterator methods and while loops etc.
To dive further into performance:

  • .sort() alters the original array, no need to reassign it, to save a bit of memory :);
  • your snippet computes sort.length on each iteration, better store it into a variable;
  • count and i have the same value, so you can remove one of them.

Note that for loop first instruction can actually be any set of declarations. So You could directly optimize the code like that:

arr.sort((a,b) => b - a);
let count = 0; // declared outside so it remains in the scope after for loop
for(const n = arr.length; count < n; count++) {
  if (arr[0] !== arr[count]) {
    return count;
  } 
}
return count;
Enter fullscreen mode Exit fullscreen mode

But anyway, .sort() on large arrays will still iterate over all elements. Put like this, it'll be more elegant and should have more or less the same perfs:

const target = Math.max(...arr); // compute once, expensive
return arr.filter(v => v === target).length; // iterate once, cheap
Enter fullscreen mode Exit fullscreen mode
Collapse
 
noclat profile image
Nicolas Torres • Edited

And if you really want the best possible perfs, the best option is to iterate once.

It could go like that:

let count = 0;
for (let i = 0, max = 0, n = arr.length; i<n; i++) {
  if (arr[i] > max) {
    max = arr[i];
    count = 1;
  } else if (arr[i] === max) {
    count++;
  }
}
return count;
Enter fullscreen mode Exit fullscreen mode