core: reserve vector sizes as much as we can (#9118)

avoid reallocations as much as possible with a few edge cases where the
reservation overshoots a tiny bit. but a few bytes of memory short term
is better used then the overhead of potential reallocation.
This commit is contained in:
Tom Englund 2025-01-19 10:38:42 +00:00 committed by GitHub
parent f56153a9c1
commit 4da9b7cc5b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 45 additions and 12 deletions

View file

@ -83,8 +83,19 @@ void CGlobalShortcutsProtocol::sendGlobalShortcutEvent(std::string appid, std::s
std::vector<SShortcut> CGlobalShortcutsProtocol::getAllShortcuts() {
std::vector<SShortcut> copy;
for (auto const& c : m_vClients) {
for (auto const& sh : c->shortcuts) {
// calculate the total number of shortcuts, precomputing size is linear
// and potential reallocation is more costly then the added precompute overhead of looping
// and finding the total size.
size_t totalShortcuts = 0;
for (const auto& c : m_vClients) {
totalShortcuts += c->shortcuts.size();
}
// reserve number of elements to avoid reallocations
copy.reserve(totalShortcuts);
for (const auto& c : m_vClients) {
for (const auto& sh : c->shortcuts) {
copy.push_back(*sh);
}
}