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

烈酒焚心 提交于 2020-01-25 07:33:26

问题


I was leetcoding and suddenly I was wondering if what's the time complexity of spread in Array. I tried researching it but haven't found any answers or is it just I'm bad at my googling skills.

I know it's just a basic or noob question but I was wondering if what is the time complexity of using spread in an Array in JavaScript. Is it linear: O(n)? Or is it constant: O(1)?

Example of syntax below:

let lar = Math.max(...nums)

Appreciate if someone could help. Thanks in advance.


回答1:


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);


来源:https://stackoverflow.com/questions/57032373/whats-the-time-complexity-of-javascript-spread-syntax-in-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!