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.")

Answer from snowfrogdev on Stack Overflow
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

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › set-vs-array-in-javascript
Set vs Array in JavaScript - GeeksforGeeks
August 5, 2025 - Sets are faster than arrays in terms of searching as they use a hash table internally for storing data and can be used to replace duplicates from other data types. ... it: It is an iterable object whose all elements are added to the new set ...
Discussions

Benchmark driven development in JavaScript (Set vs. Array)
More like microbenchmark driven nonsense, this isnt helping anyone especially sets and arrays do completly different things More on reddit.com
🌐 r/javascript
26
0
July 12, 2024
Am I wrong to think that the “has” method for Sets is better for time complexity vs “includes” for Arrays?
Looking at your example, you're already iterating on the array, so why not use !!array[i] instead? More on reddit.com
🌐 r/learnjavascript
15
1
October 13, 2020
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
Performance of SQLite in-memory database vs. native JavaScript data structures?
216k members in the node community. More on reddit.com
🌐 r/node
December 7, 2019
🌐
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]++;
}
}
})

🌐
Medium
medium.com › @yuri-lima › javascript-performance-when-set-becomes-faster-than-array-includes-0adb3134f95b
JavaScript Performance: When Set Becomes Faster Than Array.includes() | by Yuri Lima | Medium
January 31, 2025 - This led me to conduct a performance test to determine **at what point Set.has() becomes faster than **``. In this post, I’ll walk through the key differences, run a simple benchmark, and explain the results step by step. Both methods are used to check if a value exists in a collection, but they work very differently under the hood: Array.includes(value): Scans the array linearly (O(N)), checking each element one by one.
🌐
DEV Community
dev.to › programminginblood › why-sethas-is-faster-than-arrayincludes-for-finding-items-4hh
Why Set.has() is Faster Than Array.includes() for Finding Items - DEV Community
November 1, 2024 - Unlike arrays, set is built for handling unique values, so it won't have duplicate values inside of it and has more lookup times. When you use Set.has(), JavaScript can find the item in one direct operation, no matter how many items are in the set.
🌐
Sergio Carracedo
sergiocarracedo.es › js-lists-performance
Sergio Carracedo | Find a item in lists in js: Performance of Set vs Array
September 4, 2023 - Under 100k items the difference ... Rather than array that stores the values in memory, Set uses a Hashtable that is intrinsically faster than an array to find a value, as as we mentioned the Big O average is O(1...
🌐
MeasureThat
measurethat.net › Benchmarks › Show › 17071 › 0 › set-vs-array-iteration
Benchmark: set vs array iteration - MeasureThat.net
JavaScript benchmarks, JavaScript performance playground. Measure performance accross different browsers. javascript benchmarks online.
Find elsewhere
🌐
Frontend Masters
frontendmasters.com › courses › blazingly-fast-js › optimizing-code-sets-vs-array
Optimizing Code: Sets vs Array - Blazingly Fast JavaScript | Frontend Masters
ThePrimeagen discusses the performance of using sets versus arrays in JavaScript and analyzes a code example that compares the speed of finding unique characters using sets and arrays. They …
🌐
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 - While performance is important, it’s also crucial to consider the specific requirements of your application. The choice between Set, Map, Array, and Object should be based on the operations you need to perform most frequently, as well as the size of the collection.
🌐
LinkedIn
linkedin.com › pulse › array-vs-set-javascript-manvendra-singh-scjbf
Array vs Set in JavaScript
November 25, 2023 - Use a set when you need to store unique values without a specific order. Performance:Sets may have better performance for certain operations (e.g., checking for existence) due to their unique property.
🌐
DEV Community
dev.to › david4473 › set-vs-array-14c0
Set vs Array - DEV Community
October 11, 2021 - Although an array can be modified to accept unique elements, set is, however, optimized for such functionalities out of the box. If you want high-performance element lookups use set's has() method.
🌐
xjavascript
xjavascript.com › blog › javascript-set-vs-array-performance
JavaScript Set vs Array Performance: Which is Faster for Adding, Removing, and Iterating? — xjavascript.com
Benchmark Setup: Iterate over all elements in a pre-populated Array and Set using for...of. ... Iteration performance is nearly identical.
🌐
Reddit
reddit.com › r/javascript › benchmark driven development in javascript (set vs. array)
r/javascript on Reddit: Benchmark driven development in JavaScript (Set vs. Array)
July 12, 2024 - And because you can choose both and functionally it's gonna work the same then we have to look at theoretical performance (big O) but more importantly at the concrete performance characteristics of each to determine which one to use for which use-case. ... Am I wrong to think that the “has” method for Sets is better for time complexity vs “includes” for Arrays? ... Benchmark driven development in JavaScript (Set vs.
🌐
YouTube
youtube.com › thevimeagen
JS Performance: Playing Around With Sets / Arrays - YouTube
LIVE ON TWITCH: https://twitch.tv/ThePrimeagenGet in on Discord: https://discord.gg/ThePrimeagenGet in on Twitter: https://twitter.com/ThePrimeagen### Got So...
Published: July 18, 2023
Views: 10K
🌐
Medium
oluwadaprof.medium.com › sets-vs-arrays-in-javascript-0ccbca1c08a1
Sets vs Arrays in JavaScript. JavaScript gives us multiple ways to… | by Israel | Medium
January 29, 2026 - Order preserved → (✅ Array) (✅Set) Allows duplicates → (✅Array) (❌Set) Index access → (✅Array) (❌Set) Lookup performance → O(n)Array O(1)Set Built-in uniqueness → (❌Array) (✅Set) Serializable (JSON) → (✅Array) (❌Set)
🌐
GitHub
gist.github.com › Azmisov › 4d265e630ab068f945a72d3e59ea3cca
Benchmark javascript Set vs Array performance for inserting elements · GitHub
Benchmark javascript Set vs Array performance for inserting elements · Raw · set_vs_array.mjs · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Reintech
reintech.io › blog › javascript-set-vs-array-when-to-use-each
JavaScript Set vs Array: Performance Guide & When to Use Each
March 30, 2026 - The right choice depends on your specific situation, and measuring is the only way to know for sure. The key takeaway? Neither Set nor Array is universally better. They're specialized tools designed for different jobs. Master both, understand their tradeoffs, and you'll write faster, cleaner, ...
🌐
Rune Hub
rune.codes › home › tutorials › javascript › set vs array in javascript: complete guide
Set vs Array in JavaScript: Which to Use and When | Rune Hub
July 15, 2026 - Set is for uniqueness and fast membership checks. Array is for ordered lists, indexed access, and sequence manipulation. Convert between them freely and choose based on what your data needs: uniqueness or position.
🌐
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
paoladolcemascolo.medium.com › can-i-interest-you-in-a-set-the-set-vs-the-array-in-javascript-b410aad0ba9c
Can I interest you in a Set? The set vs. the array in Javascript | by Paola Dolcemascolo | Medium
March 12, 2021 - Memory usage definitely increased with the Set…with me beating 75% of submissions using an array vs beating only 48% of submissions using a set. That being said, the gain in performance was significantly better than what was sacrificed in ...