gpt4 book ai didi

Javascript:读取 ES6 Map.size 是常数时间吗?

转载 作者:行者123 更新时间:2023-11-29 21:12:21 27 4
gpt4 key购买 nike

获取对象的大小通常包括迭代和计数,或者 Object.keys(obj).length 也是 O(n)。如果我切换到 Map,我可以假设 Map.size 在 O(1) 中运行吗?

我是 Javascript 的新手,来自 C++ 世界,我很震惊我找不到一个标准来规范该语言提供的所有函数的时间复杂度。

最佳答案

你不能依赖它,除非你已经检查了源代码或凭经验证明了它的实现。 The specification表明 Map.prototype.size 是一个具有循环逻辑的 getter:

get Map.prototype.size

Map.prototype.size is an accessor property whose set accessor function is undefined. Its get accessor function performs the following steps:

  1. Let M be the this value.
  2. If Type(M) is not Object, throw a TypeError exception.
  3. If M does not have a [[MapData]] internal slot, throw a TypeError exception.
  4. Let entries be the List that is the value of M's [[MapData]] internal slot.
  5. Let count be 0.
  6. For each Record {[[Key]], [[Value]]} p that is an element of entries
    • If p.[[Key]] is not empty, set count to count+1.
  7. Return count.

但是只要 size 的语义不变,实现就可以自由优化。

关于Javascript:读取 ES6 Map.size 是常数时间吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139430/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com