var compareFn = (a, b) => a - b
var array = Array.from({ length: 500 }).map((_) => Math.random());
const result = array.sort(compareFn);
var array = Array.from({ length: 500 }).map((_) => Math.random());
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 | 11684.2 Ops/sec |
array.toSorted | 11933.8 Ops/sec |
The benchmark defined in the provided JSON compares two different methods for sorting arrays in JavaScript: array.sort()
and array.toSorted()
. Both methods are tested for their performance when sorting an array of random numbers generated with a specific length.
array.sort()
const result = array.sort(compareFn);
compareFn
) to determine the order of elements.ExecutionsPerSecond: 11684.25
array.toSorted()
const result = array.toSorted(compareFn);
ExecutionsPerSecond: 11933.78515625
toSorted()
.array.toSorted()
performs slightly better than array.sort()
in this test case, indicating potential optimizations in newer JavaScript engines.array.toSorted()
may not be available in all environments. Developers should check compatibility with their target browsers or environments._.sortBy()
which can be used for sorting. These libraries often come with additional features like chaining and handling edge cases.Float32Array
) can also be sorted utilizing their own methods, yielding potentially better performance in scenarios involving large datasets.In conclusion, both array.sort()
and array.toSorted()
are useful depending on the context of the application. array.sort()
is a legacy method with direct modification, while array.toSorted()
offers a cleaner approach when immutability is essential. The performance benchmarks suggest that toSorted()
is the preferable method in this particular test scenario, but context matters when deciding on the most appropriate option.