Fix: avoid unnecessary vector size expansion
Previously, the vector was initialized with sensorTypes.size(),
causing it to allocate empty strings upfront. However, push_back()
would still add elements, leading to the final vector being twice
the expected size.
Now, the vector is initialized empty and uses reserve() to allocate
the correct size, ensuring proper memory usage without unnecessary
allocation.
Tested:
- Before: vector contained N empty strings + N valid sensor names
- After: vector contained only the expected sensor names
Change-Id: I4c11af957dd4e780048635b14bfcdf97be69e950
Signed-off-by: Zane Li <zane.li.wiwynn@gmail.com>
diff --git a/src/Utils.hpp b/src/Utils.hpp
index cb96822..9f799f5 100644
--- a/src/Utils.hpp
+++ b/src/Utils.hpp
@@ -315,7 +315,8 @@
retries = 5;
}
- std::vector<std::string> interfaces(types.size());
+ std::vector<std::string> interfaces;
+ interfaces.reserve(types.size());
for (const auto& type : types)
{
interfaces.push_back(configInterfaceName(type));
diff --git a/src/hwmon-temp/HwmonTempMain.cpp b/src/hwmon-temp/HwmonTempMain.cpp
index cd86571..cdd7cdc 100644
--- a/src/hwmon-temp/HwmonTempMain.cpp
+++ b/src/hwmon-temp/HwmonTempMain.cpp
@@ -537,7 +537,8 @@
}
}
});
- std::vector<std::string> types(sensorTypes.size());
+ std::vector<std::string> types;
+ types.reserve(sensorTypes.size());
for (const auto& [type, dt] : sensorTypes)
{
types.push_back(type);
diff --git a/src/psu/PSUSensorMain.cpp b/src/psu/PSUSensorMain.cpp
index ad8b10f..63bc6b5 100644
--- a/src/psu/PSUSensorMain.cpp
+++ b/src/psu/PSUSensorMain.cpp
@@ -1111,7 +1111,8 @@
createSensorsCallback(io, objectServer, dbusConnection,
sensorConfigs, sensorsChanged, activateOnly);
});
- std::vector<std::string> types(sensorTypes.size());
+ std::vector<std::string> types;
+ types.reserve(sensorTypes.size());
for (const auto& [type, dt] : sensorTypes)
{
types.push_back(type);