数组中JavaScript传播语法的时间复杂度是多少? [英] What's the time complexity of JavaScript spread syntax in arrays?

查看:95
本文介绍了数组中JavaScript传播语法的时间复杂度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时是 leetcoding ,突然间我想知道在 Array 中传播的时间复杂度是多少.我尝试研究它,但是没有找到任何答案,或者仅仅是我对自己的谷歌搜索技术不满意.

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.

我知道这只是一个基本的问题,但是我想知道在 JavaScript 中在 Array 中使用扩展的时间复杂度是多少?它是线性的:O(n)?还是常数:O(1)?

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

以下语法示例:

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

感谢有人可以帮助您. 预先感谢.

Appreciate if someone could help. Thanks in advance.

推荐答案

Spread调用了有关对象的[Symbol.iterator]属性.对于数组,这将遍历数组中的每个项目,调用数组迭代器的.next()直到迭代器用尽,从而导致O(N)的复杂性.

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..of(也称为[Symbol.iterator])循环也是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);

(如果操作是O(1),则几乎是瞬时的,但不是)

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

这篇关于数组中JavaScript传播语法的时间复杂度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆