Steve
Steve

Reputation: 4533

How's the performance with '.has' and without '.has' when creating element for Set data structure?

I have this two functions which does the same thing, to insert only unique element into a set. Just wondering, how is the performance difference is it checks the element before insert verses without?

function removeAllDup(n) {
    // Set (ES6) is a collection for unique values.
    let seen = new Set;

    n.forEach(item => seen.add(item));

    return seen;
}

function removeAllDup2(n) {
    // Set (ES6) is a collection for unique values.
    let seen = new Set;

    n.forEach(element => {
        // if element does not exist in the set, add the element.
        if (!seen.has(element)) {
            seen.add(element);
        }
    })

    return seen;
}

Upvotes: 0

Views: 37

Answers (1)

Mien
Mien

Reputation: 106

Set will check the new value by itself, the 'has' check isn't needed.

Upvotes: 1

Related Questions