I have an array of 2000 authors. I need to sort by the name that has the most post, but also filter out any names that don't have any posts.
In my head im thinking filtering first, then sorting would be faster. But upon testing using Performance.now, they seem to be the same? (Tested on a small list (10-20 authors).
items.filter((item) => item.author.posts.total)
.sort(function (a, b) {
return (
b.author.posts.total -
a.author.posts.total
);
})
OR
items.sort(function (a, b) {
return (
b.author.posts.total -
a.author.posts.total
);
})
.filter((item) => item.author.posts.total)
CodePudding user response:
On small samples of data, it doesn't change anything but on large ones, it is better to filter first and then dort because js uses quicksort (which is one of the fastest algorithms today) which is O(n log n)
so the less data you have, the faster it is, and filtering shrinks the size of the sample, so filtering first is faster.
Hope it helped you !
CodePudding user response:
Tested on a small list (10-20 authors).
Performance testing means absolutely nothing unless the data in question is large enough to take a nontrivial amount of CPU to process. Even then, they're often unreliable..
That said, assuming you have a large amount of items in the array, and the array isn't sorted in any way already, it should be faster to remove the undesirable items from the array first with .filter
than to include sort them unnecessarily, then remove them afterwards. Filtering has O(n)
computational complexity; sorting has O(n log n)
complexity (if the data starts out completely unsorted).