14

I was wondering what is the time complexity of using spread with an array in JavaScript. Is it linear O(n) or constant O(1)?

Example of syntax below:

let lar = Math.max(...nums)
Jaaayz
  • 1,533
  • 7
  • 27
  • 59
  • 2
    I don't have any evidence, but it would be quite odd if it wasn't O(n). It has to iterate over every element of the array. – jhpratt Jul 15 '19 at 01:41
  • 2
    There is no spread operator, there is [*spread syntax*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). ;-) – RobG Jul 15 '19 at 01:42
  • @RobG ya sorry about that. Will edit the question :) – Jaaayz Jul 15 '19 at 01:52
  • @jhpratt ya at-least it's better to see a clearer picture that's why I asked haha. – Jaaayz Jul 15 '19 at 01:53
  • I think it will depend on the alternative you want to compare to and the implementation it's running in, e.g. in the OP, vs `Math.max.apply(null,nums)` and maybe in the case of a host object vs `Array.from(document.getElementsByTagName('p'))` or similar. – RobG Jul 15 '19 at 03:24

1 Answers1

35

Spread calls the [Symbol.iterator] property on the object in question. For arrays, this will iterate through every item in the array, calling the array iterator's .next() until the iterator is exhausted, resulting in complexity of O(N).

For the exact same reason, for..of (which also calls [Symbol.iterator]) loops are also O(N):

const arr = [1, 2, 3];
for (const item of arr) {
  console.log(item);
}

For a live example, see how the following snippet takes some time to execute:

const arr = new Array(3e7).fill(null);
const t0 = performance.now();
const arr2 = [...arr];
console.log(performance.now() - t0);

(if the operation was O(1), it'd be near instantaneous, but it isn't)

Argument spread is different from array spread, but it uses the same operation (iterates through the iterable until it's exhausted), and so has the same complexity.

For function calls:

myFunction(...iterableObj);
Community
  • 1
  • 1
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Just a note that simplistic performance tests like the above are likely heavily influenced by how different implementations do or don't optimise code. Making a change to the operations being performed can have a significant impact on relative performance that far exceeds any differences in `...`, *for..in*, *for..of*, etc. :-) – RobG Jul 15 '19 at 01:45