Simpler yes, faster no. If you look at algorithmic complexity, the sort() function has at least O(n*log(n)). Presorted merge sort (what this basicly is) has a complexity of O(n).

I think that as this is a series for relative beginners, it's important to emphasise the fact that often, simpler code is better than "faster" code. If you're working with arrays as small as in the example, the difference will be essentially negligible.

I usually take the rule that if there is any noticeable slowness in my code, then I go and try and optimise things like this, but in the vast majority of situations (I would suggest), this sort of complexity is overkill.

Yes of course, always write simple first, then measure performance and optimize where needed.
My point was that using properties like presorted arrays can allow you to go beyond the theoretical limit of O(n*log(n)) that a normal sorting algorithmus has.

## re: Merging Arrays in Javascript VIEW POST

FULL DISCUSSIONAnother solution, simple and faster.

sort an array

developer.mozilla.org/en-US/docs/W...

concat 2 arrays:

developer.mozilla.org/en-US/docs/W...

Thanks for sharing!

Simpler yes, faster no. If you look at algorithmic complexity, the

`sort()`

function has at least`O(n*log(n))`

. Presorted merge sort (what this basicly is) has a complexity of`O(n)`

.A canonical implementation would be:

As you can see, only one loop, with

`n = |a| + |b|`

executions}

I think that as this is a series for relative beginners, it's important to emphasise the fact that often, simpler code is better than "faster" code. If you're working with arrays as small as in the example, the difference will be essentially negligible.

I usually take the rule that if there is any noticeable slowness in my code, then I go and try and optimise things like this, but in the vast majority of situations (I would suggest), this sort of complexity is overkill.

Yes of course, always write simple first, then measure performance and optimize where needed.

My point was that using properties like presorted arrays can allow you to go beyond the theoretical limit of

`O(n*log(n))`

that a normal sorting algorithmus has.Absolutely, definitely useful stuff to know!