Ad

What Is The Super Fast And Prefered Way For Two Code Bellow?

My code get all online people from server But I just need just those online people that I have in my contact list.

there I have two way:

  1. having two nested loop to comare all online people with those online people I have in my conact list and then just add online people of my contact list to an Object in my App. code is below:
people = {};
myContacts = [...];
this.socket.on('online', users => {
    for (let i = users.length - 1; i >= 0; i--) {
         for (let j = myContacts.length - 1; j >= 0; j--) {
             if (myContacts[j].userid === users[i]) {
                this.people[myContacts[j].userid] = 'online';
             }
        }
    }
   this.setState({refresh: !this.state.refresh});
});
  1. having just one loop and adding all online people to an object in my App. code is below:
people = {};
myContacts = [...];
this.socket.on('online', users => {
    for (let i = users.length - 1; i >= 0; i--) {
         this.people[users[i]] = 'online';
    }
   this.setState({refresh: !this.state.refresh});
});

Now my question is: What is best way which of the above number you prefer me for having a good performance and a fast job during using the App.

**Note: Why I am worry about this although both of them works well, you think there is 10000 people online at the same time.

Here may you tell me second one is better because there is one loop, but I am confusing if we have 10000 people online on that time we will have 10000 people in the Object and accessing online people we need from the object by username may take a long time. But in first code getting people take much time because we have two loop and comparing them but accessing within the app will be easy because we just have those online people are in my contact list.**

Ad

Answer

IMHO browser's native includes() (applied to bigger array) method should be the fastest one:

for (let j = myContacts.length - 1; j >= 0; j--) {
  this.people[myContacts[j].userid] = users.includes( myContacts[j].userid ) ? 'online' : 'offline';
}

you can also store only a boolean value

for (let j = myContacts.length - 1; j >= 0; j--) {
  this.people[myContacts[j].userid] = users.includes( myContacts[j].userid );
}

and render conditionally what you need (translated message, icon, etc.)

Ad
source: stackoverflow.com
Ad