Array.sort() vs Array.toSorted() performance: which one is faster?
Tags: javascript, webdev, node
Published: 2024-03-11 14:30:00

In an effort to free the world from side effects, it comes natural to think about `Array.toSorted()` and – as it normally happens when immutability is the topic – be worried about performance.

For once, as it doesn't sort in place, it feels like `.toSorted()` may be not just a healthier, but also a faster alternative to `.sort()`. Is that true?

```bash
nvm install 20
```

Let's find out.

A few big fat arrays with or without duplicates is what we need to make the party fun and varied.

```js
a = [...Array(1_000_000)]
  .map((_, i) => i)
  .toSorted(()=>Math.random()-.5)
```

One million items, each ranging from 0 to 1 million, no duplicates.

## `.sort()`
```js
const sortFn = () => { 
  t1=performance.now();
  for(i=0;i<10;i++){
    b=[...a];
    b.sort();
  }
  t2=performance.now();
  console.log(t2-t1)
};

> 18411.447928994894
```
## `.toSorted()`
Now, see `.toSorted()` in action
```js
const toSortedFn = () => { 
  t1=performance.now();
  for(i=0;i<10;i++){
    b=[...a];
    b.toSorted();
  }
  t2=performance.now();
  console.log(t2-t1)
};

> 17944.199489980936
```

Got a verdict? Not really.

I've been using a laptop, `11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz`, with a power governor on and obviously you can tell.
If we re-run the above tests, we keep getting randomly varying results. Sometimes `.sort()` is faster, sometimes `.toSorted()` is.

Ok, so if CPU throttling is interacting with our tests, maybe we could increase the size of the array or do more repetitions to have more cores running hot for more similar periods of time.

```javascript
a1 = [...Array(10_000_000)]
  .map((x, i) => i)
  .toSorted(()=>Math.random()-.5)
```

10 million items x10, starting with all cores around 50°C/122°F See what happens.

(had to close dev.to whilst writing this article, as it was running useless JavaScript on 90% CPU and heating up cores for nothing. Damn JavaScript programmers! LOL)

```
toSorted: 37761.23623800278
sort: 39893.87974700332

toSorted: 40070.24533998966
sort: 36632.13215699792

toSorted: 39103.39215800166
sort: 35256.66026097536
```

Been waiting for CPUs to cool down before running each test, and in this case, `.sort()` appeared to be performing better 2 times out of 3. Still nothing convincing.

## Dupes?
In the above tests, the array `a` had 1M and 10M unique values respectively. Will adding some dupes make any difference?

```javascript
a=[];
for(i=0;i<10_000_000;i++)a.push(parseInt(Math.random()*10_000))


sortFn();
> 33331.32965299487
toSortedFn();
> 32472.87901800871
sortFn();
> 33025.877364993095
toSortedFn();
> 33994.72117897868
```

In this case the difference doesn't appear as relevant at all. Tried another case with 100 different values, and the total time converged as much as 21466ms vs 21807ms.


## (Interim) Conclusion
This was a bit of an extreme benchmark and a number of external factors were at play, which makes results a bit questionable.
My interpretation and conclusion so far is that in "normal" use cases `Array.sort()` and `Array.toSorted()` don't have any significant difference in performance.

That means, if we are making a choice between sorting in place and having side-effects-free code, we can lean towards `Array.toSorted()` without worries and will gain in terms of maintainability.