Overview
Optimizing in C++ means knowing your environment. One should know how vector works, and vector works with pushing back elements into an array.
Advantages of std::vector
Dynamic arrays in C++ are implemented using std::vector
.
When a new element is inserted, and the existing capacity of the vector is exhausted, the std::vector
resizes itself. The way it does that is by allocating memory at a different location that is large enough to fit the element we are inserting as well as the existing items. Then it copies all the existing items into the new location and adds the element we are trying to insert.
The standard vector resizes itself very frequently when elements get pushed into it. It results in multiple memory reallocations and slower, inefficient code. To avoid resizing and copying, we can use the reserve
function. If we know how many elements the vector will hold, we can reserve that size at the beginning. Reserve
will make sure that we have enough memory. Thus, multiple memory reallocations will be avoided whenever new elements are inserted into the vector.
How is this feature integrated with Embold?
Embold has integrated a checker in C++.
performance-inefficient-vector-operation
: It finds possible inefficientstd::vector
operations (e.g.:push_back
) that may cause unnecessary memory reallocations.
Example:
std::vector v;
for (int i = 0; i < n; ++i) {
v.push_back(n);
}
An explanation for the above example
The push_back
function may cause multiple memory reallocations in v. Avoid by inserting a ‘reserve(n)
‘ statement before the ‘for’ statement.
std::vector<int> v;
v.reserve(n);
for (int i = 0; i < n; ++i) {
v.push_back(n);
}
Conclusion
We are spending too much time on reallocating and deallocating memory. However, by using the C++ function std::vector::reserve
, it helps to reserve the vector capacity that may contain at least n elements.
Also, it is recommended the usage of std::vector
in most cases where dynamic arrays are needed. And this optimizing by using a standard vector will lead to easily resizing the length.
Comments are closed.