Array.includes() VS Set.has()

I am sure after reading this article you will be happy :) from this article, you will learn how to optimize your code and increase performance by these examples.
Array.includes and Set.has() both used for searching for a specific value within an array or set.

  • Array.includes() has a time complexity o(n)
  • Set.has() has a time complexity o(1)

So using Set.has() in your codebase has a great impact on the performance which enhances the performance.

Let’s explain by example.

In this example, we will get user’s information who are online. We have two arrays now. the users array which represents all users exist in the database and the sessions array which stores online users ids. We will compare the performance when using both Array.includes() and Set.has() to see the impact.

10 users in db and 2 online users

const users = [
    { id: 1, name: 'AvisBoehm', email: 'Garry.Cartwright@gmail.com' },
    { id: 2, name: 'MagnoliaLabadie', email: 'Gwendolyn46@gmail.com' },
    { id: 3, name: 'RylanAnkunding', email: 'Cora53@gmail.com' },
    { id: 4, name: 'ChelsieReynolds', email: 'Jaylen_Hilll32@gmail.com' },
    { id: 5, name: 'VerdieCole', email: 'Lilliana.Altenwerth@yahoo.com' },
    { id: 6, name: 'IsaacWeissnat', email: 'Casimir.Johns@gmail.com' },
    { id: 7, name: 'ClayMarquardt', email: 'Dandre66@hotmail.com' },
    { id: 8, name: 'LilyanMacejkovic', email: 'Tyra20@gmail.com' },
    { id: 9, name: 'VivianneSchimmel', email: 'Everette60@hotmail.com' },
    { id: 10, name: 'FeltonGreenfelder', email: 'Katherine25@gmail.com' },
];
console.time("includes");
const sessions =[2,10];
const onlineUsersArr = users.filter((user)=>{
    return  sessions.includes(user.id)
});
console.timeEnd("includes");
console.time("set");
const onlineUserSet = new Set(sessions);
const onlineUsersSet = users.filter((user)=>{
    return  onlineUserSet.has(user.id)
});
console.timeEnd("set");
/*
 * The result of running this script 
 * includes: 0.088ms
 * set: 0.026ms
 */

100k users in DB and 10 online users

Now If we need to apply the same but data will be large to see the difference and impact.

  • Create a new NodeJS project by creating new directory arrayXset.
  • Inside project directory run the following command npm init -y.
  • Create two files index.js , users.json and faker.js
  • Install the follwoing package faker by running the command npm i faker which used for generating random data.
  • Make sure that users.json file has a write permission if not run the following command chmod 777 users.json

in faker.js add the following code and run it by running the following command node faker.js

const faker = require("faker");
const fs = require("fs");
const users = [];
for(let start=1;start<=100000;start++){
    let user = {"id":start,"email":`${faker.internet.email()}`,"name":`${faker.name.firstName()} ${faker.name.firstName()}`}
    users.push(user);
}
fs.writeFileSync("./users.json",`{"users":${JSON.stringify(users)}}`);

After running this script users.json file contains 100k users
in index.js

const {users} = require("./users.json");
const sessions = new Array(10);
for(let start=1;start<=10;start++){
    sessions[start]=start;
}
const onlineUserSet = new Set(sessions);

console.time("includes");
users.filter((user)=>{
    return  sessions.includes(user.id)
});
console.timeEnd("includes");
console.time("set");
users.filter((user)=>{
    return  onlineUserSet.has(user.id)
});
console.timeEnd("set")
/*
 * The result
 * includes: 4.892ms
 * set: 3.906ms
 */

100k users in DB and 100 online users

const {users} = require("./users.json");
const sessions = new Array(100);
for(let start=1;start<=100;start++){
    sessions[start]=start;
}
const onlineUserSet = new Set(sessions);

console.time("includes");
users.filter((user)=>{
    return  sessions.includes(user.id)
});
console.timeEnd("includes");
console.time("set");
users.filter((user)=>{
    return  onlineUserSet.has(user.id)
});
console.timeEnd("set")
/*
 * The result
 * includes: 16.288ms
 * set: 4.134ms
 */

100k users in DB and 1k online users

// const faker = require("faker");
// const fs = require("fs");
// const users = [];
// for(let start=1;start<=100000;start++){
//     let user = {"id":start,"email":`${faker.internet.email()}`,"name":`${faker.name.firstName()} ${faker.name.firstName()}`}
//     users.push(user);
// }
// fs.writeFileSync("./users.json",`{"users":${JSON.stringify(users)}}`);
//after writing process
const {users} = require("./users.json");
const sessions = new Array(1000);
for(let start=1;start<=1000;start++){
    sessions[start]=start;
}
const onlineUserSet = new Set(sessions);

console.time("includes");
users.filter((user)=>{
    return  sessions.includes(user.id)
});
console.timeEnd("includes");
console.time("set");
users.filter((user)=>{
    return  onlineUserSet.has(user.id)
});
console.timeEnd("set")
/*
 * The result
 * includes: 99.533ms
 * set: 3.646ms
 */

Finally, you are happy? :) Just like and share also subscribe to newsletter.

Subscribe to our Newsletter

Subscribe to tech-hour website to get all updates, new articles, new courses and projects. No spam ever. Unsubscribe at any time.