From 38933e478a0d749aa18f54947a85818393b845a5 Mon Sep 17 00:00:00 2001 From: Warm Beer Date: Thu, 2 Nov 2023 09:12:16 +0100 Subject: [PATCH] refactor: Optimize `Tracker.update_torrent_with_peer_and_get_stats` by reducing torrent list writes --- src/tracker/mod.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index f3a057f09..958554f6e 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -439,7 +439,6 @@ pub mod services; pub mod statistics; pub mod torrent; -use std::collections::btree_map::Entry; use std::collections::{BTreeMap, HashMap}; use std::net::IpAddr; use std::panic::Location; @@ -722,11 +721,16 @@ impl Tracker { // code-review: consider splitting the function in two (command and query segregation). // `update_torrent_with_peer` and `get_stats` - let mut torrents = self.torrents.write().await; + let maybe_existing_torrent_entry = self.torrents.read().await.get(info_hash).cloned(); - let torrent_entry = match torrents.entry(*info_hash) { - Entry::Vacant(vacant) => vacant.insert(Arc::new(Mutex::new(torrent::Entry::new()))), - Entry::Occupied(entry) => entry.into_mut(), + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.torrents.write().await; + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(Mutex::new(torrent::Entry::new()))); + entry.clone() }; let mut torrent_entry_lock = torrent_entry.lock().await;