![](/img/trans.png)
[英]Why is there a difference in the naming of `Array.prototype.includes` vs `Set.prototype.has`?
[英]Why is Set.prototype.has() much faster than Array.prototype.includes()? Node v10
我有兩個字符串數組,長度都為 ~150000。 我想找到兩者之間的共享元素,所以我在 array1 上使用了 filter(),並檢查每個元素是否 array2.includes[array1element]。 這大約需要 1.5 分鍾才能完成執行,但是當我將數組更改為集合並使用 set2.has(set1element) 時,它會在 <1 秒內執行以進行過濾。 我將 set1 的內容展開到一個數組中,但是使用 Set.prototype.has() 在 set2 上進行搜索。
我是集合的新手,實際上我才發現它們是因為數組需要很長時間來搜索,而我正在尋找替代方案。 有人可以解釋為什么會有這么大的時差嗎? 我沒有太多的數學背景,所以對數學/算法術語較少的答案表示贊賞!
代碼:其中wireBpath 和wireApath 是字符串數組:運行時間~1.5 分鍾
let intersections = wireBpath.filter(position => wireApath.includes(position));
其中,wireBpath 是一個數組(從集合傳播以使用 filter() 方法),wireApath 是一個集合:runtime<1s
let intersections = wireBpath.filter(position => wireApath.has(position));```
那是因為Set
和Array
the time complexity
不同
Sets 用於搜索項目的方法的時間復雜度僅為O(1)
,但數組用於搜索項目的方法具有O(N)
的線性時間復雜度。 換句話說,運行時間隨着數據大小的增加而增加。
有關更多詳細信息,您可以查看這篇文章
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.