0

In my code, if I call vector::reserve(capacity) and allocate more capacity than what I actually need for the vector to hold the elements, then during the running of my program, will the vector always holds the memory, not releasing resource and costs? If so, isn't that kind of memory waste?

Can I risk trying to lower the reserve capacity to the anticipated size of vector and would that make the program run robust and maybe faster?

Would this lower the possibility of running out of memory?

I ran the code on the mobile phone with high computative load tasks, so still need to consider memory overhead.

anc
  • 191
  • 1
  • 19
  • 2
    Yes, it will always have the reserved amount of memory, unless the actual size of the vector grows beyond that and it will get reallocated as usual. As far as the rest of your questions, that's for you to decide. – Sam Varshavchik Jul 27 '17 at 12:30
  • Once you filled the vector, you can always [shrink the capacity to fit the size](http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit). – Some programmer dude Jul 27 '17 at 12:31

1 Answers1

1

will the vector always holds the memory, not releasing resource and costs kind of memory waste?

The vector will not release/reallocate the memory.

If it had reallocated the memory, then all the iterators, references and pointers referencing the elements stored in that vector will be invalidated without notice.

Can I risky trying to lower the reserve(capacity) to the anticipated size of vector and make the program run robust and maybe faster?

I'd say that a good practice is to call reserve if you know that the vector size will reach eventually a constant size, or has a minimum size. otherwise, lose the call to reserve. let the vector do its own calculations. you will realize that the vector reallocations are probably not the bottleneck of your program.

You can also call shrink_to_fit to make sure that your vector uses exactly the amount of memory it needs.

David Haim
  • 25,446
  • 3
  • 44
  • 78
  • this answer doesnt parse right. You are saying that a vector *will* release memory ("No , it won't"). And that it does this because its how it can be sure not to invalidate pointers and references – pm100 Jul 27 '17 at 15:25
  • 1
    I rephrased it . – David Haim Jul 27 '17 at 15:27