title: How to keep track of players' rankings?
body: <p>I have a <code>Player</code> class with a <code>score</code> attribute:</p>
  
  <pre><code>class Player(game_engine.Player):
  
      def __init__(self, id):
          super().__init__(id)
          self.score = 0
  </code></pre>
  
  <p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell the player his rank out of the total amount of players with something like</p>
  
  <pre><code>print('Your rank is {0} out of {1}')
  </code></pre>
  
  <p>First I thought of having a list of all the players, and whenever anything happens to a player:</p>
  
  <ol>
  <li>I check if his score increased or decreased</li>
  <li>find him in the list</li>
  <li>move him until his score is in the correct place</li>
  </ol>
  
  <p>But this would be <em>extremely</em> slow. There can be hundreds of thousands of players, and a player can reset his own score to <code>0</code> which would mean that I'd have to move everyone after him in the stack. Even finding the player would be O(n).</p>
  
  <p>What I'm looking for is a high performance solution. RAM usage isn't quite as important, although common sense should be used. How could I improve the system to be a lot faster?</p>
  
  <p><strong>Updated info:</strong> I'm storing a player's data into a MySQL database with SQLAlchemy everytime he leaves the gameserver, and I load it everytime he joins the server. These are handled through <code>'player_join'</code> and <code>'player_leave'</code> events:</p>
  
  <pre><code>@Event('player_join')
  def load_player(id):
      """Load player into the global players dict."""
      session = Session()
      query = session.query(Player).filter_by(id=id)
      players[id] = query.one_or_none() or Player(id=id)
  
  @Event('player_leave')
  def save_player(id):
      """Save player into the database."""
      session = Session()
      session.add(players[id])
      session.commit()
  </code></pre>
  
  <p>Also, the player's score is updated upon <code>'player_kill'</code> event:</p>
  
  <pre><code>@Event('player_kill')
  def update_score(id, target_id):
      """Update players' scores upon a kill."""
      players[id].score += 2
      players[target_id].score -= 2
  </code></pre>