Looking at relative numbers only is always dangerous, here are some absolute numbers, run on NodeJS v14.14.0 on an Intel 8350U:

Iterations Object write Object read Map write Map read
100 0ms 0ms 0ms 0ms
1.000 3ms 1ms 0ms 0ms
10,000 7ms 4ms 8ms 1ms
1.000.000 1222ms 527ms 632ms 542ms

So as one can see, for 10.000 iterations the difference between objects and maps is 1 millisecond in the run above, and as that is the accuracy of the time measurement, we can't really derive any conclusion from that test. The results are absolutely random.

For 1 Million iterations one can see a clear advantage of Map writes over Object writes, the read performance is very similar. Now if we look at absolute numbers, this is still one million writes / s. So although object writes are a lot slower, this will unlikely be the bottleneck of your application.

For an accurate explanation, one would have to analyze all the steps the engine performs. For that you can run node --print-code and analyze the bytecode that gets run. I don't have the time for that, though here are some observations:

  1. If the object gets constructed with Object.create(null) (having no prototype) the performance is about the same, so prototype lookup does not influence performance at all.

  2. After the 20th iteration, V8 chooses the internal representation dictionary_map for object, so this is basically one hash map competing with another hashmap (one can run node --allow-natives-syntax and then use %DebugPrint(object) to get the internal representation).

  3. For objects with more than 2 ** 23 keys, write performance degrades even more, see Performance degrade on JSObject after 2^23 items (though maps also can‘t be much larger - see Maximum number of entries in Node.js Map? )

For reference, here is the code used to run the benchmark:

Show code snippet

function benchmark(TIMES) {  
  console.log("BENCHMARK ", TIMES);

  const object = Object.create(null);

    let start = Date.now();
    for (let i = 0; i < TIMES; ++i) {
        object[`key_${i}`] = 1;
    }

    console.log("Object write took", Date.now() - start);
    start = Date.now();

    let result = 0;
  
    for (let i = 0; i < TIMES; ++i) {
      result += object[`key_${i}`];
    }

    console.log("Object read took", Date.now() - start);
    start = Date.now();

  


  const map = new Map();
  
  for (let i = 0; i < TIMES; ++i) {
    map.set(`key_${i}`, 1);
  }
  
  console.log("Map write took", Date.now() - start);
  start = Date.now();

  result = 0;
  
  for (let i = 0; i < TIMES; ++i) {
    result += map.get(`key_${i}`);
  }

  console.log("Map read took", Date.now() - start);

}

benchmark(100);
benchmark(1_000);
benchmark(10_000);
benchmark(1_000_000);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

To sum up:

  • Use Maps for dictionaries with lots of different, changing keys as they are slightly better than objects internally represented as hash table
  • Use Objects for - well - objects. If you have a low number of keys and frequently access those, Objects are way faster (as the engine can use inline caching, hidden classes with fixed memory layout etc.)
Answer from Jonas Wilms on Stack Overflow
🌐
Medium
medium.com › @dm_md › unveiling-the-speed-of-javascript-collections-set-vs-map-vs-array-vs-object-3f6e44f24505
Unveiling the Speed of JavaScript Collections: Set vs. Map vs. Array vs. Object | by Dmytro Demchenko | Medium
March 17, 2024 - Use Set when you need to store unique values and perform fast lookups. Use Map when you need to associate values with keys and perform fast lookups based on keys. Use Array when you need to maintain an ordered collection of items and perform ...
Discussions

ecmascript 6 - Javascript set vs array vs object definition - Stack Overflow
A value in the Set may only occur once; it is unique in the Set's collection." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set · Removing values, interestingly enough, when dealing with small amounts of data, there isn't much performance difference between ... More on stackoverflow.com
🌐 stackoverflow.com
I discovered Set exists for the first time today... Is it really faster?
I use sets, maps, and spread syntax all the time. I’ve never “done the math” to see the specs of the speed for sets. Maps have methods that are way faster when trying to search and filter things in big data sets. More on reddit.com
🌐 r/learnjavascript
26
11
July 24, 2024
JavaScript Set vs. Array performance - Stack Overflow
Another interesting point is that Objects do not have officially guaranteed order, whereas Set in JavaScript is implemented as an OrderedSet and does maintain the order of insertion. Both Set and Object have their "has" method performing in what seems to be amortized to O(1), but depending ... More on stackoverflow.com
🌐 stackoverflow.com
Is the ES 2015 Map object slow?

Here's a util for comparing them. Objects do out perform Maps for get/set operations

https://jsperf.com/es6-map-vs-object-properties/73

Good on you for continuing to look though. Don't fall into the "five monkeys" trap of coding.

More on reddit.com
🌐 r/javascript
13
3
August 7, 2018
Top answer
1 of 1
41

Looking at relative numbers only is always dangerous, here are some absolute numbers, run on NodeJS v14.14.0 on an Intel 8350U:

Iterations Object write Object read Map write Map read
100 0ms 0ms 0ms 0ms
1.000 3ms 1ms 0ms 0ms
10,000 7ms 4ms 8ms 1ms
1.000.000 1222ms 527ms 632ms 542ms

So as one can see, for 10.000 iterations the difference between objects and maps is 1 millisecond in the run above, and as that is the accuracy of the time measurement, we can't really derive any conclusion from that test. The results are absolutely random.

For 1 Million iterations one can see a clear advantage of Map writes over Object writes, the read performance is very similar. Now if we look at absolute numbers, this is still one million writes / s. So although object writes are a lot slower, this will unlikely be the bottleneck of your application.

For an accurate explanation, one would have to analyze all the steps the engine performs. For that you can run node --print-code and analyze the bytecode that gets run. I don't have the time for that, though here are some observations:

  1. If the object gets constructed with Object.create(null) (having no prototype) the performance is about the same, so prototype lookup does not influence performance at all.

  2. After the 20th iteration, V8 chooses the internal representation dictionary_map for object, so this is basically one hash map competing with another hashmap (one can run node --allow-natives-syntax and then use %DebugPrint(object) to get the internal representation).

  3. For objects with more than 2 ** 23 keys, write performance degrades even more, see Performance degrade on JSObject after 2^23 items (though maps also can‘t be much larger - see Maximum number of entries in Node.js Map? )

For reference, here is the code used to run the benchmark:

Show code snippet

function benchmark(TIMES) {  
  console.log("BENCHMARK ", TIMES);

  const object = Object.create(null);

    let start = Date.now();
    for (let i = 0; i < TIMES; ++i) {
        object[`key_${i}`] = 1;
    }

    console.log("Object write took", Date.now() - start);
    start = Date.now();

    let result = 0;
  
    for (let i = 0; i < TIMES; ++i) {
      result += object[`key_${i}`];
    }

    console.log("Object read took", Date.now() - start);
    start = Date.now();

  


  const map = new Map();
  
  for (let i = 0; i < TIMES; ++i) {
    map.set(`key_${i}`, 1);
  }
  
  console.log("Map write took", Date.now() - start);
  start = Date.now();

  result = 0;
  
  for (let i = 0; i < TIMES; ++i) {
    result += map.get(`key_${i}`);
  }

  console.log("Map read took", Date.now() - start);

}

benchmark(100);
benchmark(1_000);
benchmark(10_000);
benchmark(1_000_000);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

To sum up:

  • Use Maps for dictionaries with lots of different, changing keys as they are slightly better than objects internally represented as hash table
  • Use Objects for - well - objects. If you have a low number of keys and frequently access those, Objects are way faster (as the engine can use inline caching, hidden classes with fixed memory layout etc.)
Top answer
1 of 2
34

Every value in a set has to be unique, but in Array you can push same value as many times as you'd like.

"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Removing values, interestingly enough, when dealing with small amounts of data, there isn't much performance difference between the two (Array and Set), but when you start to deal with big data, removal is a lot faster in Sets vs Arrays.

Adding values to Array is 4 times faster than adding them to set.

Iterating through the values Array is here also better performer (Growing exponentially based on the amount of data).

You can read more about the performance differences at; Javascript Set vs. Array performance

"At 10k elements, both tests ran comparable times (array: 16.6 ms, set: 20.7 ms) but when dealing with 100k elements, the set was the clear winner (array: 1974.8 ms, set: 83.6 ms) but only because of the removing operation. Otherwise the array was faster. I couldn't say exactly why that is."

Count unique items in object Set Vs Object write-up https://github.com/anvaka/set-vs-object

TL:DR Set is almost two times faster than Object.

Why Set was introduced (My guess)?

There are sometimes when you need an easy way to build up a collection of values and you have to make sure each value is unique. This brings a lot overhead away from the old fashioned check if array has the value or not and then push or skip.

This scenario was not covered in the performance post I linked earlier, but doing fast experiment on Array of 10,000 items and then adding 15 items where 5 were duplicates to the combined collection, adding to array with checking for duplicate values and skipping if duplicate it took 74ms and with set just using the set.add(value) it took 9ms.

When would you need this?

One real life example that came to my mind is that if you have an email marketing letter and you for example would have options; - TV - Music - Movies - Sports

One day your client or you would like to have only one email option for TV, Music and Movies called "Entertainment". You would need to build up a new collection based on the data from these 3 different values and you would need to make sure each email are added to the new entertainment emailing list only once. Meaning that users could've opted-in for Movies as well as TV if they are interested in both.

Here you could just make set Entertainment and then iterate through all the lists TV/Music/Movies and use Entertainment.add(email) and the set would take care of skipping values that already exists in the list. Hence avoiding duplicate emails in the emailing list.

Also set would be optimal format to store your email subscriber addresses, as nobody could accidentally opt-in twice for you emails.

2 of 2
0

Basically, set is used to store elements uniquely whereas in arrays, you can duplicate the elements. And regarding objects, in use cases when you also need to store additional information regarding each element, then you would choose object over set and array.

For example: storing info. of your apps users, which include their name, phone no., address, email etc. Then in objects, you can define a key, let's say email (or you could also create a unique id), then keys in your object would be email (or the other one) and the additional info about the user would get stored as properties.

🌐
Azurewebsites
benchmarklab.azurewebsites.net › Benchmarks › Show › 20838 › 0 › set-vs-object-vs-map-a4vw343v43
Benchmark: Set vs Object vs Map a4vw343v43 - MeasureThat.net
✓ Object: 183,454,880 ops/sec · • Set: 6,352,754 ops/sec · • Map: 4,265,877 ops/sec · Results show median performance across all community submissions. Run this benchmark yourself to verify on your device. Rendered benchmark preparation results: Run tests (3) Previous results Fork ·
🌐
GitHub
gist.github.com › Chunlin-Li › 2606bd813df88eaeee2d
node / javascript performance : Set vs Object and Map vs Object · GitHub
TL;DR: Objects: slowest key access, slowest key write. Sets: fastest key access, fastest key write.
🌐
Mostly Focused
mostlyfocused.com › pages › articles › maps_or_sets
Should You Use JavaScript Maps And Sets? - mostlyFOCUSED
October 13, 2024 - It is true that the Map.delete function is faster than the object delete keyword, but there's a catch. The Map.set function is slower than the object's internal set method, so whatever bonus you might get from faster deletes would get a huge ...
Find elsewhere
🌐
MeasureThat
measurethat.net › Benchmarks › Show › 5364 › 0 › set-vs-object-vs-map
Benchmark: Set vs Object vs Map - MeasureThat.net
✓ Object: 83,637,968 ops/sec · • Set: 1,933,875 ops/sec · • Map: 1,395,035 ops/sec · Results show median performance across all community submissions. Run this benchmark yourself to verify on your device. Rendered benchmark preparation results: Run tests (3) Previous results Fork ·
🌐
CodeHints
codehints.io › blog › map-set-object-javascript
JavaScript Data Structures - Choosing Between Map, Set, and Object | CodeHints
They perform well in scenarios where the main operation is to add elements and check for their existence. Objects: Traditionally, Objects were not optimized for frequent additions and deletions. However, modern JavaScript engines have significantly improved Object performance.
🌐
Reddit
reddit.com › r/learnjavascript › i discovered set exists for the first time today... is it really faster?
r/learnjavascript on Reddit: I discovered Set exists for the first time today... Is it really faster?
July 24, 2024 -

I was working through a problem in Angular, and finally had all the data I wanted to process pieced together.

I am very curious whether Set() is a common thing these days and whether I should consider learning more about these ES6 operator even if nobody on my team has ever used them (I have the least experience by a mile).

My first instinct was to go for an array, but then I asked ChatGPT to help me finish up the code, and it switched to a Set(). When I asked why, it said Set() is faster and excludes duplicates from the array.

The task consisted of:

Array 1: An array of arrays (a ton of data inside them),
Array 2: An array of 2+ objects with some string properties
Array 3: An array of objects with about 90 objects in it

The purpose is:

  1. Loop through each object of Array 1 and find if the status string is what we want. If so we add the ID from that object to the targetId's Set().

  2. Use the list of 90 objects and check if the ID we added in Step 1 exists in an object somewhere in there

  3. If it exists in there, use the item.category to access the number value from categoryCounts object and increment it.

Here is a generic version of the code:

const categoryCounts: {
[category: string]: number
} = {};
// Extract IDs from the data
const targetIds = new Set < number > ();
const segments = [
...data.segmentOneArray,
...data.segmentTwoArray,
...data.segmentThreeArray,
...data.segmentFourArray,
];
segments.forEach((segment) => {
if (segment.status === "statusWeWant" && segment.itemId) {
targetIds.add(segment.itemId);
}
});
// Process the item list to count occurrences for each category
itemList.forEach(item => {
if (targetIds.has(Number(item.itemId))) {
const category = item.category;
if (filteredCategories.some(c => c.description === category)) {
if (!categoryCounts[category]) {
categoryCounts[category] = 0;
}
categoryCounts[category]++;
}
}
})

🌐
egghead.io
egghead.io › lessons › javascript-use-es6-sets-to-improve-javascript-performance
Use ES6 Sets to Improve Javascript Performance | egghead.io
Using Sets in ES6 to produce lists of unique objects is faster than using arrays, and less error prone than using objects. In this lesson, we explore th...
Published: January 5, 2019
🌐
Medium
osgoodgunawan.medium.com › map-vs-set-vs-object-in-javascript-7345b455afcd
Map vs. Set vs. Object in Javascript | by Osgood Gunawan | Medium
December 14, 2020 - However, ECMAScript 2015 introduced two new types of iterable objects: Sets and Maps; these are ‘keyed collections,’ which means their behavior is slightly different and offers performance advantages. There are two main differences between Map and a traditional Object in Javascript.
🌐
MeasureThat
measurethat.net › Benchmarks › Show › 15186 › 0 › set-has-vs-object-key
Benchmark: Set has vs object key - MeasureThat.net
Object.keys(object).includes(key) vs key in object · Set has vs object key reversed · array includes vs object key vs set · Set has vs object key 3 · Comments · Do you really want to delete benchmark?
🌐
OpenReplay
blog.openreplay.com › openreplay blog › what's the difference between map, set, and object in javascript?
What's the Difference Between Map, Set, and Object in JavaScript?
February 21, 2026 - Maps outperform Objects for frequent additions and deletions, whereas Objects excel at read-heavy workloads with stable shapes. Sets provide O(1) membership checks and now ship with native union, intersection, and difference methods in modern ...
🌐
LogRocket
blog.logrocket.com › home › es6 keyed collections: maps and sets
ES6 keyed collections: Maps and sets - LogRocket Blog
June 4, 2024 - In this guide, we’ll take a closer look at maps and sets and examine their syntax, how they differ from objects and arrays, and what methods they offer. We’ll also compare their performance. JavaScript sets resemble arrays in the sense that they are also collections of values.
Top answer
1 of 7
182

Ok, I have tested adding, iterating and removing elements from both an array and a set. I ran a "small" test, using 10 000 elements and a "big" test, using 100 000 elements. Here are the results.

Adding elements to a collection

It would seem that the .push array method is about 4 times faster than the .add set method, no matter the number of elements being added.

Iterating over and modifying elements in a collection

For this part of the test I used a for loop to iterate over the array and a for of loop to iterate over the set. Again, iterating over the array was faster. This time it would seem that it is exponentially so as it took twice as long during the "small" tests and almost four times longer during the "big" tests.

Removing elements from a collection

Now this is where it gets interesting. I used a combination of a for loop and .splice to remove some elements from the array and I used for of and .delete to remove some elements from the set. For the "small" tests, it was about three times faster to remove items from the set (2.6 ms vs 7.1 ms) but things changed drastically for the "big" test where it took 1955.1 ms to remove items from the array while it only took 83.6 ms to remove them from the set, 23 times faster.

Conclusions

At 10k elements, both tests ran comparable times (array: 16.6 ms, set: 20.7 ms) but when dealing with 100k elements, the set was the clear winner (array: 1974.8 ms, set: 83.6 ms) but only because of the removing operation. Otherwise the array was faster. I couldn't say exactly why that is.

I played around with some hybrid scenarios where an array was created and populated and then converted into a set where some elements would be removed, the set would then be reconverted into an array. Although doing this will give much better performance than removing elements in the array, the additional processing time needed to transfer to and from a set outweighs the gains of populating an array instead of a set. In the end, it is faster to only deal with a set. Still, it is an interesting idea, that if one chooses to use an array as a data collection for some big data that doesn't have duplicates, it could be advantageous performance wise, if there is ever a need to remove many elements in one operation, to convert the array to a set, perform the removal operation, and convert the set back to an array.

Array code:

var timer = function(name) {
  var start = new Date();
  return {
    stop: function() {
      var end = new Date();
      var time = end.getTime() - start.getTime();
      console.log('Timer:', name, 'finished in', time, 'ms');
    }
  }
};

var getRandom = function(min, max) {
  return Math.random() * (max - min) + min;
};

var lastNames = ['SMITH', 'JOHNSON', 'WILLIAMS', 'JONES', 'BROWN', 'DAVIS', 'MILLER', 'WILSON', 'MOORE', 'TAYLOR', 'ANDERSON', 'THOMAS'];

var genLastName = function() {
  var index = Math.round(getRandom(0, lastNames.length - 1));
  return lastNames[index];
};

var sex = ["Male", "Female"];

var genSex = function() {
  var index = Math.round(getRandom(0, sex.length - 1));
  return sex[index];
};

var Person = function() {
  this.name = genLastName();
  this.age = Math.round(getRandom(0, 100))
  this.sex = "Male"
};

var genPersons = function() {
  for (var i = 0; i < 100000; i++)
    personArray.push(new Person());
};

var changeSex = function() {
  for (var i = 0; i < personArray.length; i++) {
    personArray[i].sex = genSex();
  }
};

var deleteMale = function() {
  for (var i = 0; i < personArray.length; i++) {
    if (personArray[i].sex === "Male") {
      personArray.splice(i, 1)
      i--
    }
  }
};

var t = timer("Array");

var personArray = [];

genPersons();

changeSex();

deleteMale();

t.stop();

console.log("Done! There are " + personArray.length + " persons.")

Set code:

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            console.log('Timer:', name, 'finished in', time, 'ms');
        }
    }
};

var getRandom = function (min, max) {
  return Math.random() * (max - min) + min;
};

var lastNames = ['SMITH','JOHNSON','WILLIAMS','JONES','BROWN','DAVIS','MILLER','WILSON','MOORE','TAYLOR','ANDERSON','THOMAS'];

var genLastName = function() {
    var index = Math.round(getRandom(0, lastNames.length - 1));
    return lastNames[index];
};

var sex = ["Male", "Female"];

var genSex = function() {
    var index = Math.round(getRandom(0, sex.length - 1));
    return sex[index];
};

var Person = function() {
	this.name = genLastName();
	this.age = Math.round(getRandom(0,100))
	this.sex = "Male"
};

var genPersons = function() {
for (var i = 0; i < 100000; i++)
	personSet.add(new Person());
};

var changeSex = function() {
	for (var key of personSet) {
		key.sex = genSex();
	}
};

var deleteMale = function() {
	for (var key of personSet) {
		if (key.sex === "Male") {
			personSet.delete(key)
		}
	}
};

var t = timer("Set");

var personSet = new Set();

genPersons();

changeSex();

deleteMale();

t.stop();

console.log("Done! There are " + personSet.size + " persons.")

2 of 7
94

OBSERVATIONS:

  • Set operations can be understood as snapshots within the execution stream.
  • We are not before a definitive substitute.
  • The elements of a Set class have no accessible indexes.
  • Set class is an Array class complement, useful in those scenarios where we need to store a collection on which to apply basic addition, Deletion, checking and iteration operations.

I share some test of performance. Try to open your console and copypaste the code below.

Creating an array (125000)

var n = 125000;
var arr = Array.apply( null, Array( n ) ).map( ( x, i ) => i );
console.info( arr.length ); // 125000

1. Locating an Index

We compared the has method of Set with Array indexOf:

Array/indexOf (0.281ms) | Set/has (0.053ms)

// Helpers
var checkArr = ( arr, item ) => arr.indexOf( item ) !== -1;
var checkSet = ( set, item ) => set.has( item );

// Vars
var set, result;

console.time( 'timeTest' );
result = checkArr( arr, 123123 );
console.timeEnd( 'timeTest' );

set = new Set( arr );

console.time( 'timeTest' );
checkSet( set, 123123 );
console.timeEnd( 'timeTest' );

2. Adding a new element

We compare the add and push methods of the Set and Array objects respectively:

Array/push (1.612ms) | Set/add (0.006ms)

console.time( 'timeTest' );
arr.push( n + 1 );
console.timeEnd( 'timeTest' );

set = new Set( arr );

console.time( 'timeTest' );
set.add( n + 1 );
console.timeEnd( 'timeTest' );

console.info( arr.length ); // 125001
console.info( set.size ); // 125001

3. Deleting an element

When deleting elements, we have to keep in mind that Array and Set do not start under equal conditions. Array does not have a native method, so an external function is necessary.

Array/deleteFromArr (0.356ms) | Set/remove (0.019ms)

var deleteFromArr = ( arr, item ) => {
    var i = arr.indexOf( item );
    i !== -1 && arr.splice( i, 1 );
};

console.time( 'timeTest' );
deleteFromArr( arr, 123123 );
console.timeEnd( 'timeTest' );

set = new Set( arr );

console.time( 'timeTest' );
set.delete( 123123 );
console.timeEnd( 'timeTest' );

Read the full article here

🌐
CodeBurst
codeburst.io › array-vs-set-vs-map-vs-object-real-time-use-cases-in-javascript-es6-47ee3295329b
Array vs Set vs Map vs Object — Real-time use cases in Javascript (ES6/ES7) | by Rajesh Babu | codeburst
March 28, 2023 - Note: Compared to the array’s includes function, Object’s hasOwnProperty and Set/Map’s has functions seem to perform close to O(1) in different tests, clearly more efficient in terms of larger data sets.
🌐
DEV Community
dev.to › shafayeat › optimizing-javascript-with-maps-sets-and-weak-references-i3g
Optimizing JavaScript with Maps, Sets, and Weak References - DEV Community
October 16, 2024 - Sets vs. Arrays Sets are an excellent alternative to arrays when dealing with unique values. They automatically eliminate duplicates, and the lookup performance is superior due to their hash-based implementation.
🌐
Timveletta
timveletta.com › blog › array-set-object-map
Array vs Set vs Object vs Map - Tim Veletta
August 18, 2023 - Adding to an Object or a Map has constant time complexity. However, there is a bit of a gotcha with the Map code below. If we run this in JavaScript, it wouldn’t complain. However, we might notice that henry doesn’t get added in the way we expect.