api/api.hh: use std::vector::reserve() when the total size is known

When growing via push_back(), std::vector may need to reallocate
its internal block of memory due to not enough space. It is advised
to allocate the required space before appending elements if the
size is known beforehand.

This change introduces usage of std::vector::reserve() in api.hh
to ensure that push_back() does not cause reallocations.

Signed-off-by: Patryk Wrobel <patryk.wrobel@scylladb.com>
This commit is contained in:
Patryk Wrobel
2024-01-25 08:50:15 +01:00
parent 1007ac4956
commit 1ca71f2532

View File

@@ -26,6 +26,8 @@ namespace api {
template<class T>
std::vector<sstring> container_to_vec(const T& container) {
std::vector<sstring> res;
res.reserve(std::size(container));
for (auto i : container) {
res.push_back(fmt::to_string(i));
}
@@ -35,6 +37,8 @@ std::vector<sstring> container_to_vec(const T& container) {
template<class T>
std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) {
std::vector<T> res;
res.reserve(map.size());
for (auto i : map) {
res.push_back(T());
res.back().key = i.first;
@@ -45,6 +49,8 @@ std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) {
template<class T, class MAP>
std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) {
res.reserve(res.size() + std::size(map));
for (auto i : map) {
T val;
val.key = fmt::to_string(i.first);
@@ -64,6 +70,8 @@ T map_sum(T&& dest, const S& src) {
template <typename MAP>
std::vector<sstring> map_keys(const MAP& map) {
std::vector<sstring> res;
res.reserve(std::size(map));
for (const auto& i : map) {
res.push_back(fmt::to_string(i.first));
}