From cd36d82153ca3a553350ab6a9763258922c5e1ae Mon Sep 17 00:00:00 2001 From: chaowyc Date: Wed, 12 Nov 2025 22:41:33 +0800 Subject: [PATCH 1/2] perf: optimize _peer_to_session from std::map to std::unordered_map Replace std::map with std::unordered_map for _peer_to_session to achieve O(1) lookup performance instead of O(log n). The peer_t type (ENetPeer*) is a pointer, which has native hash support. All operations (find, emplace, erase) are interface-compatible between std::map and std::unordered_map. This change aligns with the code comment at line 529 which states: 'Insert this into the map for O(1) lookups in the future' Tested: - Interface compatibility verified with unit test - Performance benchmark confirms expected improvements - No API changes required (drop-in replacement) --- src/stream.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/stream.cpp b/src/stream.cpp index e6bb5ebfde2..294c94b600a 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -318,7 +318,7 @@ namespace stream { sync_util::sync_t> _sessions; // ENet peer to session mapping for sessions with a peer connected - sync_util::sync_t> _peer_to_session; + sync_util::sync_t> _peer_to_session; ENetAddress _addr; net::host_t _host; From 17f7f075663109d0fcdefb42f7f7712275579a20 Mon Sep 17 00:00:00 2001 From: chaowyc Date: Thu, 13 Nov 2025 00:03:54 +0800 Subject: [PATCH 2/2] fix: correct append_struct reserve calculation and optimize insertion This patch fixes two issues in append_struct(): 1. Fixed reserve() calculation: Changed from reserve(data_len) to reserve(buf.size() + data_len) to correctly account for existing buffer size. The original code could fail to allocate sufficient space when the buffer already contains data. 2. Optimized insertion: Replaced loop with N push_back() calls with a single insert() operation, reducing function call overhead and avoiding potential mid-loop reallocations. --- src/utility.h | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/utility.h b/src/utility.h index db5d7f9d24d..085ecc271c8 100644 --- a/src/utility.h +++ b/src/utility.h @@ -202,13 +202,10 @@ namespace util { void append_struct(std::vector &buf, const T &_struct) { constexpr size_t data_len = sizeof(_struct); - buf.reserve(data_len); + buf.reserve(buf.size() + data_len); // Reserve enough space upfront auto *data = (uint8_t *) &_struct; - - for (size_t x = 0; x < data_len; ++x) { - buf.push_back(data[x]); - } + buf.insert(buf.end(), data, data + data_len); } template