var array = Array.from({ length: 10_000 }).map((_) => Math.random());
var compareFn = (a, b) => a - b
const result = array.toSorted(compareFn)
const result = array.sort(compareFn);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.toSorted | |
array.sort |
Test name | Executions per second |
---|---|
array.toSorted | 376.6 Ops/sec |
array.sort | 5324.9 Ops/sec |
The benchmark provided compares two methods of sorting arrays in JavaScript: array.sort()
and array.toSorted()
. This test evaluates the performance difference between these two sorting methods in terms of how many times they can be executed per second.
array.sort(compareFn)
:
array.toSorted(compareFn)
:
array.sort()
, it also accepts a comparison function for custom sort orders.array.sort()
Pros:
Cons:
array.toSorted()
Pros:
Cons:
In the benchmark results:
array.sort()
executed 4729.66 times per second.array.toSorted()
executed only 796.33 times per second.This indicates that array.sort()
performs significantly better in this particular benchmark, likely due to its in-place sorting mechanism compared to the memory overhead of creating a new sorted array with array.toSorted()
. Depending on the context of usage, if performance is critical and the data does not need to be preserved, array.sort()
may be favored. However, if immutability is required or preferred, array.toSorted()
is the better choice despite the performance tradeoff.
Other alternatives for sorting arrays in JavaScript include:
In summary, this benchmark provides a straightforward comparison between two critical sorting methods in JavaScript, illustrating usage scenarios, performance implications, and considerations regarding immutability.