From 4fcf7328144269624655c77508d30f0c966d6120 Mon Sep 17 00:00:00 2001 From: Shubhankar Sarangi Date: Sun, 24 Nov 2024 15:58:45 +0530 Subject: [PATCH] impr: Reserve space to avoid multiple allocations when loading scripts (#1929) std::forward ensures that the arguments are perfectly forwarded to loadScript By reserving space in the features vector based on the size of scripts, we can avoid multiple memory allocations during the loop. If an exception occurs, returning an empty vector immediately clarifies that no scripts were loaded. Without reservation, each call to emplace_back could potentially trigger a reallocation if the current capacity is exceeded, which is costly in terms of performance. This leads to more efficient memory management and can significantly speed up the execution time when dealing with a large number of scripts. ![image](https://github.com/user-attachments/assets/3e290162-fb8b-4f00-a71b-6009494b2dab) --- .../source/plugin_script_loader.cpp | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/plugins/script_loader/source/plugin_script_loader.cpp b/plugins/script_loader/source/plugin_script_loader.cpp index 5e5238886..2c58dd676 100644 --- a/plugins/script_loader/source/plugin_script_loader.cpp +++ b/plugins/script_loader/source/plugin_script_loader.cpp @@ -32,32 +32,33 @@ namespace { scripts.emplace_back(&script); } - std::vector loadAllScripts() { - std::vector scripts; +std::vector loadAllScripts() { + std::vector scripts; - try { - std::apply([&scripts](auto&&... args) { - (loadScript(scripts, args), ...); - }, s_loaders); - } catch (const std::exception &e) { - log::error("Error when loading scripts: {}", e.what()); - } - - { - std::vector features; - for (const auto &script : scripts) { - if (!script->background) - continue; - - features.emplace_back(script->name, true); - } - - IMHEX_PLUGIN_FEATURES = features; - } - - return scripts; + try { + std::apply([&scripts](auto&&... args) { + (loadScript(scripts, std::forward(args)), ...); + }, s_loaders); + } catch (const std::exception &e) { + log::error("Error when loading scripts: {}", e.what()); + return {}; } + std::vector features; + features.reserve(scripts.size()); + + for (const auto &script : scripts) { + if (script->background) { + features.emplace_back(script->name, true); + } + } + + IMHEX_PLUGIN_FEATURES = std::move(features); + + return scripts; +} + + void initializeLoader(u32 &count, auto &loader) { try { if (loader.initialize())