简体   繁体   中英

javascript - Set vs Map - which is faster?

Set and Map both are newer data types in es6 and for certain situations both can be used.

eg - if i want to store all unique elements, i can use Set as well as Map with true as value.

const data: string[] ;
        // console.log('data', data[0])
        const set = new Set();
        const map = new Map<string, boolean>();
        
 
        data.forEach((item) => {
            map.set(item, true);
        });
         

         
        data.forEach((item) => {
            set.add(item);
        });
   

Both works, but i was wondering which one is faster ?

Update 1

  1. I am looking for which of the data structure is faster in case of storing data.

  2. checking if value exist using -

map.has(<value>)
set.has(<value>)
  1. deleting values

Also i can understand true is redundant and not used anywhere, but i am just trying to show how map and set can be used alternatively.

What matters is speed.

In the most basic sense:

  • Maps are for holding key-value pairs
  • Sets are for holding values

The true in your map is completely redundant ... if a key exists, that automatically implies, that it is true/exists - so you will never ever need to use the value of the key-value pair in the map (so why use the map at all, if you're never gonna make use of what it is actually for? - to me that sounds like a set/array with extra steps)

If you just want to store values use an array or set. - Which of the two depends on what you are trying to do.

The question of "which is faster" can't really be answered properly, because it largely depends on what you are trying to do with the stored values. (What you are trying to do also determines what data structure to use)

So choose whatever data structure you think fits your needs best, and when you run into a problem that another would fix, you can always change it later/convert from one into another.

And the more you use them and the more you see what they can and can not do, the better you'll get at determining which to use from the start (for a given problem)

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