Skip to main content

Command Palette

Search for a command to run...

Reserve your space in vector. Serioulsy, DO IT

Updated
1 min read
Reserve your space in vector. Serioulsy, DO IT
R

I am a C++ developer with expertise in building solutions for onboard embedded devices and products, has a penchant for building REST API backends with Spring boot and Node JS express framework

Skill Cloud: MQTT, IoT, SSL, HTTP, TLS, REST API, curl, Node JS, Express, Java, Spring Boot, MongoDB

Always reserve space for vector in advance if you know the expected size of a vector, this avoids reallocations which happen frequently when a vector gradually grows and breaches available capacity
Note that, every time this breach happens, a new allocation is done which is a costly operation

To understand, why we need to reserve, we need to know the difference between size and capacity of a vector and how does a vector allocate memory dynamically, Read it here, https://cppnuggets.hashnode.dev/size-vs-capacity-in-a-vector

#include <vector>
int main()
{
    // 1. Naive method, without reserve
    std::vector<int> box;
    for( int index = 0; index < 50; index++)
        box.push_back(50);

    // 2. With reserve
    std::vector<int>another_box;
    another_box.reserve(50);
    for( int index = 0; index < 50; index++)
        box.push_back(50);
}

In first method, vector will need to allocate memory dynamically and copy elements to new memory block, whenever limit exceeds.

In second method, with reserve, memory for 50 elements will be allocated in one shot, thus avoiding the need of further allocations. In vector lingo, another_box will be assigned with capacity of 50,
Hence, we wont need further reallocations

A
Anтo4y ago

interesting and fast to read, I hope to see new articles in that way !

1
R

Glad you like it, I'll keep'em coming !!!

More from this blog

cppnuggets

15 posts

Just as the name says, we'll enjoy learning C++, one nugget at a time ☕