From 2f97bc2baedb3eeec7dff220bba0c647867baa29 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Mon, 19 Feb 2024 20:08:28 +0100 Subject: [PATCH] feat(sdk): Improve performance of `EventCacheInner::for_room`. --- crates/matrix-sdk/src/event_cache/mod.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/matrix-sdk/src/event_cache/mod.rs b/crates/matrix-sdk/src/event_cache/mod.rs index 7eb4c0f76..5fd14c7ac 100644 --- a/crates/matrix-sdk/src/event_cache/mod.rs +++ b/crates/matrix-sdk/src/event_cache/mod.rs @@ -269,9 +269,21 @@ impl EventCacheInner { /// /// It may not be found, if the room isn't known to the client. async fn for_room(&self, room_id: &RoomId) -> RoomEventCache { + // Fast path: the entry exists; let's acquire a read lock, it's cheaper than a + // write lock. + let read_guard = self.by_room.read().await; + + if let Some(room) = read_guard.get(room_id) { + return room.clone(); + } + + // Slow-path: the entry doesn't exist; let's acquire a write lock. + drop(read_guard); + self.by_room .write() .await + // Use `Entry` to avoid race condition. .entry(room_id.to_owned()) .or_insert_with(|| { // Create the new `RoomEventCache`.