array = Array.from({
length: 50
}, (x, i) => (Math.round(Math.random() * (i + .01) * 1000)))
sortNumeric = (a, b) => (Number(a) - Number(b));
array.sort(sortNumeric);
array.toSorted(sortNumeric)
[array].sort(sortNumeric);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.sort() | |
Array.toSorted() | |
[...Array].sort() |
Test name | Executions per second |
---|---|
Array.sort() | 147144.2 Ops/sec |
Array.toSorted() | 0.0 Ops/sec |
[...Array].sort() | 65389.5 Ops/sec |
This benchmark compares the performance of three different ways to sort an array in JavaScript: Array.sort()
, Array.toSorted()
, and the spread operator with Array.sort()
([...array].sort()
). The goal is to determine which of these methods performs better in terms of execution speed.
sortNumeric
is defined to sort numbers in ascending order:sortNumeric = (a, b) => (Number(a) - Number(b));
Array.sort(sortNumeric):
Array.sort()
Array.toSorted(sortNumeric):
Array.toSorted()
0.0
executions per second, indicating that it may not be implemented or functioning correctly in the environment tested.[...array].sort(sortNumeric):
[...Array].sort()
Array.sort():
Array.toSorted():
0.0
executions per second, which suggests it may not work in the tested environment or across all browsers.[...array].sort():
Array.sort()
, it sorts while preserving the original array since it operates on a copy. It’s useful when the original array state needs to remain unchanged.Array.sort()
performs the best in terms of execution speed compared to the alternatives. The Array.toSorted()
indicates a failure or poor support in the tested environment, making it less reliable for use.In conclusion, if performance is crucial, Array.sort()
might be preferred, but if the integrity of the original array must be preserved, it may be worth exploring Array.toSorted()
(ensuring it’s supported in the target environment) or the spread operator method.