Use Vector: reserve to avoid unnecessary reallocation

Source: Internet
Author: User

One of the most commendable features of STL containers is that they can automatically grow to be enough to accommodate the data you put in as long as they do not exceed their maximum size. (To know the maximum value, you only need to call the member function named max_size .) For vector and string, if more space is needed, increase the size in a way similar to realloc. This operation similar to realloc has four parts:

  1. Allocate a new memory block, which has a multiple of the current container capacity. In most implementations, the capacity of vector and string increases by 2 each time. That is to say, when containers must expand, their capacity doubles each time.
  2. Copy all elements from the old memory of the container to its new memory.
  3. Destroys objects in the old memory.
  4. Reclaim old memory.

Given all the allocation, recycling, copying, and destructor, you should know that those steps are expensive. Of course, you do not want to execute them more frequently than necessary. If this is not a blow to you, you may think that every time these steps occur, all iterators, pointers, and references pointing to the vector or string will become invalid, it will attack you. This means that simply inserting an element into a vector or string requires updating other data structures that use an iterator, pointer, or reference pointing to a vector or string.

 

The reserve member function allows you to minimize the number of times that must be re-allocated, so you can avoid overhead of true allocation and expiration of iterator/pointer/reference. But before I explain why reserve can do that, let me briefly introduce the four sometimes confusing member functions. In standard containers, only vector and string provide all these functions.

  • Size () tells you how many elements are in the container. ItNoIt tells you how much memory the container has allocated for the elements it holds.
  • Capacity () tells you how many elements a container can hold in its allocated memory. The container is in that memory.TotalHow many elements can be accommodated, rather than how many elements can be accommodated. If you want to know how much memory is not occupied in a vector or string, you must subtract size () from capacity (). If size and capacity return the same value, there is no space left in the container, and the next insertion (through insert or push_back) will lead to the above re-allocation step.
  • Resize (Container: Size_type N) to force the container to accommodate n elements. After Resize is called, size returns n. If n is smaller than the current size, the elements at the end of the container are destroyed. If n is greater than the current size, the new default element is added to the tail of the container. If n is greater than the current capacity, it will be reassigned before the element is added.
  • Reserve (Container: Size_type N) force the container to change its capacity to at least N, and the provided n is not smaller than the current size. This forces a redistribution because the capacity needs to increase. (If n is smaller than the current capacity, vector ignores it. This call does nothing. String may reduce its capacity to size () and N in large numbers, however, the size of the string is not changed. In my experience, it is generally better to use reserve to Trim excess capacity from a string than to use "exchange skills", which is the subject of Clause 17 .) [1]

This introduction indicates that as long as there are elements to be inserted and the container capacity is insufficient, they will be re-allocated (including the original memory allocated and recycled they maintain, object copy and analysis structure and iterator, pointer and reference failure ). Therefore, the key to avoiding reallocation is to use reserve to set the container capacity to large enough as soon as possible. It is best to do so immediately after the container is constructed.

For example, suppose you want to create a vector containing 1-values <int>. If reserve is not used, you can do it like this:

vector<int> v;for (int i = 1; i <= 1000; ++i) v.push_back(i);

In most STL implementations, this code will cause two to ten Re-allocations during the loop process. (10 is nothing strange. Remember that when the redistribution happens, the vector generally doubles the capacity, and 1000 is about 210 .)

Change the code to use reserve. We get this:

vector<int> v;v.reserve(1000);for (int i = 1; i <= 1000; ++i) v.push_back(i);

This will not happen in the loop.

The relationship between size and capacity allows us to predict when insertion will cause the vector or string to be re-allocated, and, it can be predicted when insertion will invalidate the iterator, pointer, and reference pointing to the container. For example, the following code is provided,

string s;...if (s.size() < s.capacity()) {s.push_back('x');}

Push_back does not invalidate the iterator, pointer, or reference pointing to this string, because the size of the string must be greater than its size. If push_back is not executed and the code performs an insert operation at any position of the string, we can still ensure that no redistribution occurs during the insertion. However, it is consistent with the general rule that the iterator becomes invalid when it is inserted with string. All iterators, pointers, and references from the inserted position to the end of the string will become invalid.

 

Back to the purpose of these terms, reserve is usually used in two cases to avoid unnecessary redistribution. The first available scenario is when you know exactly or approximately how many elements will last in the container. In that case, just like the vector code above, you just reserve the appropriate amount of space in advance. The second case is to keep the maximum space you may need, and then, once you add full data, trim any excess capacity.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.