简体   繁体   中英

Why is Set.prototype.has() much faster than Array.prototype.includes()? Node v10

I have two arrays of strings, both having a length of ~150000. I wanted to find shared elements between the two, so I used filter() on array1, and for each element checked if array2.includes[array1element]. this was taking around 1.5 mins to finish executing, however when I changed the arrays to sets, and used set2.has(set1element), it executed in <1s to filter. I spread the contents of set1 into an array, but searching is being done on set2 using Set.prototype.has().

I'm new to sets, I actually just discovered them because arrays were taking so long to search through and I was looking for alternatives. Can someone explain why there is such a significant time difference? I don't have much of a maths background so answers with less mathematical/algorithmic jargon are appreciated!

CODE: where wireBpath and wireApath are arrays of strings: runtime ~1.5mins

let intersections = wireBpath.filter(position => wireApath.includes(position));

where wireBpath is an array(spread from a set to use the filter() method), and wireApath is a set: runtime<1s

let intersections = wireBpath.filter(position => wireApath.has(position));```


That is because the time complexity is different for Set and Array

The methods used by Sets to search for items has a time complexity of just O(1) , but the methods an array uses to search for items has a linear time complexity of O(N) . In other words, the run-time increases at the same rate as the size of the data increases.

For more details you can see this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM