Home > Software design >  discordjs role.members.has() takes over 100ms to execute
discordjs role.members.has() takes over 100ms to execute

Time:01-04

I have a role with about 650 members in it, I'm trying to find if my given member id is in the members of that role.

I'm doing:

role.members.has(id) (or role.members.get(id)) in a loop, for some smaller sets it takes less than 5ms. With collections of 500 it takes 100ms for each check, which is way too long for a simple .get, am I doing something wrong?

CodePudding user response:

The role.members getter is an O(n) operation which is why your current code is performing poorly:

get members() {
  return this.guild.members.cache.filter(m => m.roles.cache.has(this.id));
}

Like the other answer says, you should instead be fetching the member directly and then checking for the role with GuildMemberRoleManager.cache.has().

Fetching a member by ID and then checking their cached roles are all O(1) operations which should be much more performant.

CodePudding user response:

This isnt guaranteed to work any more efficiently but I would assume fetching the member and checking that specific members roles would be more efficient than filtering cache.

const member = await <Guild>.members.fetch(id);
if(member.roles.cache.has(<Role>){
  ...
};
  •  Tags:  
  • Related