Somewhat of a basic question, while iterating through a array of objects, I need to build up a list of unique strings, would adding an if statement in a loop be better than creating a set ?
if (!arr.includes(newString)) arr.push(newString)
VS push all strings and then
arr = [ ...new Set(arr) ]
CodePudding user response:
The Set
is much, much faster.
Let's do a test on jsbench.me
Setup:
Let's create an array with numbers 0-9999, and then 0-9999 again for 20,000 items, each of which has exactly one duplicate.
const data = []
for (let i = 0; i < 10000; i ) data.push(i)
for (let i = 0; i < 10000; i ) data.push(i)
Loop Test:
let arr = []
for (let n of data) {
if (!arr.includes(n)) arr.push(n)
}
9.72 executions per second
Set test:
let arr = [ ...new Set(data) ]
1422.54 executions per second
So the Set
is 146 times faster (on my machine)
I suspect it's because Set
is implemented with native compiled code, which simple cannot be beat for performance and efficiency when done properly. And you can trust that the browsers implementations of builtins are probably very very good.
Also pretty much anything you can do to avoid loops over large arrays is a good thing for performance.