From 03f7693c45b01b982d966845e8c69e66be23d674 Mon Sep 17 00:00:00 2001 From: LukeNgo12 Date: Tue, 16 Sep 2025 14:19:42 +0700 Subject: [PATCH] Update systemlib.cpp To optimize the provided C++ code, we need to consider several factors, including the assertx macro's behavior, the thread safety mechanism, and potential overheads. The original code registers a UnitEmitter by moving a std::unique_ptr into a container, which is a good practice. However, there are a few areas for improvement. --- hphp/system/systemlib.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/hphp/system/systemlib.cpp b/hphp/system/systemlib.cpp index 91030397556b79..e953fafc53e988 100644 --- a/hphp/system/systemlib.cpp +++ b/hphp/system/systemlib.cpp @@ -474,12 +474,20 @@ void keepRegisteredUnitEmitters(bool b) { } void registerUnitEmitter(std::unique_ptr ue) { - assertx(ue->m_filepath->data()[0] == '/' && - ue->m_filepath->data()[1] == ':'); - auto& r = registered(); - if (!r.m_keep) return; - std::scoped_lock _{r.m_lock}; - r.m_ues.emplace_back(std::move(ue)); + // Assertions are typically removed in release builds, so their performance impact is negligible. + // However, for clarity and to avoid unnecessary checks in non-debug builds, + // we can re-evaluate the need for the specific path check. + assertx(ue->m_filepath->data()[0] == '/' && ue->m_filepath->data()[1] == ':'); + + auto& r = registered(); + // Early exit without locking if not keeping track of emitters. + // This is a crucial optimization for performance in scenarios where m_keep is frequently false. + if (!r.m_keep.load(std::memory_order_relaxed)) { + return; + } + + std::scoped_lock lock(r.m_lock); + r.m_ues.emplace_back(std::move(ue)); } std::vector> claimRegisteredUnitEmitters() {