Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the time complexity of JavaScript spread syntax in arrays?

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)
like image 964
Jaaayz Avatar asked Jul 15 '19 01:07

Jaaayz


1 Answers

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);
like image 170
CertainPerformance Avatar answered Nov 03 '22 00:11

CertainPerformance