var array = Array.from({ length: 10_000 }).map((_) => Math.random());
var compareFn = (a, b) => a - b
const result = [array].sort(compareFn);
const result = array.toSorted(compareFn)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
[...array].sort | |
array.toSorted |
Test name | Executions per second |
---|---|
[...array].sort | 349.9 Ops/sec |
array.toSorted | 319.3 Ops/sec |
The benchmark described in the provided JSON tests two different methods for sorting an array in JavaScript: the traditional approach using the sort()
method along with the spread operator ([...]
), and the newer toSorted()
method introduced in ECMAScript 2022.
[...array].sort(compareFn)
This approach involves creating a shallow copy of the original array using the spread operator ([...]
) and then sorting it in place using the sort()
method, which is provided by the Array prototype. The sort operation is conducted based on the comparison function compareFn
, defined as a - b
, which sorts numbers in ascending order.
array.toSorted(compareFn)
This method also sorts the array based on the provided comparison function but does so without mutating the original array. The toSorted()
method returns a new, sorted array while leaving the original array intact.
[...array].sort()
Pros:
Cons:
array.toSorted()
Pros:
Cons:
sort()
method.Performance Metrics: In the benchmark results provided, the array.toSorted
method executes slightly faster than the [...array].sort()
method (approximately 939.67 executions per second vs. 916.91). However, this performance difference can vary based on the JavaScript engine, machine specifications, and the nature of the data being sorted.
Browser Compatibility: Given that toSorted()
is newer, developers must consider its compatibility across different browsers, particularly for projects requiring support for older versions of browsers.
Beyond these two methods, there are alternative sorting strategies in JavaScript, such as:
array.sort()
directly, without the spread operator, which may be the simplest for simply sorting and using the original array.This benchmark provides a valuable comparison of two different sorting methods in JavaScript, highlighting their respective utilities, efficiencies, and suitable use cases. This is especially helpful for developers looking to enhance performance while writing maintainable and clear code.