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);letcount=0;// declared outside so it remains in the scope after for loopfor(constn=arr.length;count<n;count++){if(arr[0]!==arr[count]){returncount;}}returncount;
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:
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 :);sort.length
on each iteration, better store it into a variable;count
andi
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:
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:And if you really want the best possible perfs, the best option is to iterate once.
It could go like that: