Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

e.g - 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.

like image 850
Ujjwal Kumar Gupta Avatar asked Nov 28 '25 17:11

Ujjwal Kumar Gupta


1 Answers

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)

like image 122
Lord-JulianXLII Avatar answered Dec 01 '25 05:12

Lord-JulianXLII