C & C++

C & C++

Made by DeepSource

Inefficient use of std::vector in loop CXX-P2007

Performance
Major

Manually appending a significant number of elements to a std::vector without reserving the memory upfront can cause performance issues as the memory needs to be reallocated and copied every time the std::vector's size increases. This can be costly if many items need to be pushed into the std::vector.

Consider using the std::vector::reserve() function to preallocate memory for the std::vector before a loop containing a std::vector::push_back.

Or declare the std::vector with the required size. eg: std::vector<T>(size, value)

Bad practice

#include <vector>

// Example 1
std::vector<int> v;
for (int num = 0; num < 100000; ++i) {
  v.push_back(num); // This will trigger multiple memory reallocation for `v`
}

// Example 2
std::vector<int> copy_from;
for(auto num: copy_from) {
  v.push_back(num); // This will also trigger multiple memory reallocation for `v`
}

// Example 3
std::vector<int> vec_with_zeros;
for(auto _ : copy_from) {
  vec_with_zeros.push_back(0); // This will also trigger multiple memory reallocations for `vec_with_zeros`
}

Recommended

#include <vector>

// Example 1
std::vector<int> v;
v.reserve(100000); // Allocate memory before iteration
for (int num = 0; num < 100000; ++i) {
  v.push_back(num); // Memory is already allocated so insertion will be faster now
}

// Example 2
std::vector<int> copy_from;
v.reserve(copy_from.size()); // Allocate memory before iteration
for(auto num: copy_from) {
  v.push_back(num); // Memory is already allocated so insertion will be faster now
}

// Example 3
std::vector<int> vec_with_zeros(copy_from.size(), 0);