
本文是对
new Set的一些思考,以及去寻找答案的过程 🤔🤔🤔,应该会比答案本身更有意思,不足之处还望指点
1. Set的访问机制
下面是ECMAScript2015中Set Objects摘取的一部分
Set objects must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structures used in this Set objects specification is only intended to describe the required observable semantics of Set objects. It is not intended to be a viable implementation model.
找到需要的概念:Set Object必须使用哈希表或者其他机制,访问时间与集合中元素的数量成线性关系。
2. 线性关系
线性关系是什么?
以下参考 维基百科:
如果一个算法的时间复杂度为O(n),则称这个算法具有线性时间,或O(n)时间。非正式地说,这意味着对于足够大的输入,运行时间增加的大小与输入成线性关系。例如,一个计算列表所有元素的和的程序,需要的时间与列表的长度成正比。这个描述是稍微不准确的,因为运行时间可能显著偏离一个精确的比例,尤其是对于较小的n。
时间复杂度曲线:

3. Set.prototype相关的时间复杂度
| 操作 | 时间复杂度 |
|---|---|
| Set.prototype.get() | O(1) ~ O(logn) |
| Set.prototype.add() | O(1) ~ O(logn) |
| Set.prototype.has() | O(1) ~ O(logn) |
| Set.prototype.forEach() | O(n) |
| Set.prototype.entries() | O(n) |
| Set.prototype.values() | O(n) |
| Set.prototype.keys() | O(n) |
4. new Set()本身的时间复杂度
new Set(ArrayList[])这个操作本身的时间复杂度是多少?
4.1 Set的定义
摘取Set的定义:
Set objects are collections of ECMAScript language values. A distinct value may only occur once as an element of a Set’s collection. Distinct values are discriminated using the SameValueZero comparison algorithm.
可以看到定义中表示Set使用了SameValueZero比较算法来区分不同的值。
4.2 SameValueZero
下面是SameValueZero的内部实现规则:
The internal comparison abstract operation SameValueZero(x, y),
where x and y are ECMAScript language values, produces true or false.
Such a comparison is performed as follows:
1.ReturnIfAbrupt(x).
2.ReturnIfAbrupt(y).
3.If Type(x) is different from Type(y), return false.
4.If Type(x) is Undefined, return true.
5.If Type(x) is Null, return true.
6.If Type(x) is Number, then
If x is NaN and y is NaN, return true.
If x is +0 and y is −0, return true.
If x is −0 and y is +0, return true.
If x is the same Number value as y, return true.
Return false.
7.If Type(x) is String, then
If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices) return true; otherwise, return false.
8.If Type(x) is Boolean, then
If x and y are both true or both false, return true; otherwise, return false.
9.If Type(x) is Symbol, then
If x and y are both the same Symbol value, return true; otherwise, return false.
Return true if x and y are the same Object value. Otherwise, return false.
下图是SameValueZero和其他判断是否相等方式的一些比较:

4.3 小结
new Set根据上面的规则做去重操作,如果使用空间去换时间,那最优的时间复杂度应该是O(n)?
5.结论
能力有限,不敢定论👋,回去继续搬砖
资料参考: