sqcp icon indicating copy to clipboard operation
sqcp copied to clipboard

Speeding up the getAllOnlinePlayers

Open milutinke opened this issue 1 year ago • 0 comments

There are a couple of things that can be done to optimize the code:

  1. Reduce unnecessary usage of forEach and using map and flat instead. It's faster to generate an array in one pass with map than to use forEach to push into an array.
  2. Avoid calling PopulationUtils.getTeamNameFromId() in each iteration when the teamID doesn't change frequently. Cache the team names in a Map where the key is the teamID and the value is the team name.
  3. Use a custom sorting function that leverages the fact that playerID is a numeric value.

Proposed revision:

getAllOnlinePlayers(state) {
  const teamNameCache = new Map();

  const getTeamNameFromId = (teamID) => {
    if (!teamNameCache.has(teamID)) {
      teamNameCache.set(teamID, PopulationUtils.getTeamNameFromId(state.population.teams, teamID));
    }

    return teamNameCache.get(teamID);
  };

  const players = state.population.teams.flatMap(team =>
    team.squads.flatMap(squad =>
      squad.players.map(player => ({
        ...player,
        squad: squad.name,
        team: team.name
      }))
    )
  );

  const onlinePlayers = state.population.players.onlinePlayers
    .filter(player => !player.squadID || player.squadID === 'N/A')
    .map(player => {
      const playerCopy = {...player, squadID: undefined};
      return {
        ...playerCopy,
        squad: 'Unassigned',
        team: getTeamNameFromId(playerCopy.teamID)
      };
    });

  const allPlayers = players.concat(onlinePlayers);

  allPlayers.sort((player1, player2) => player1.playerID - player2.playerID);

  return allPlayers;
}

TODO: Test

milutinke avatar May 26 '23 08:05 milutinke