+ 2

Array vs Vector : memory management

Hi, I have a bit idea that vector is dynamic and hence it requires more memory compared to array... My query is why so..what is that and how is that which ask for more memory in case of vector...? If i reserve 4 element for vector well in advance and on the other hand , i have array of four elements... Does both consumes same memory or not ?

14th Jan 2020, 8:54 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 ответов
+ 4
From my own understanding, the std::vector object will always have some small memory overhead because it uses variables to keep track of its size and capacity, and furthermore, it might allocate some additional memory for more capacity to accomodate for future expansions, so it doesn't have to reallocate the dynamic array every time a new value is inserted. I guess when and how much additional capacity is allocated depends on the implementation. But I would suppose that after a manual reserve the raw underlying array would have the same size as a basic array allocated by you, so that effectively only the overhead caused by the extra variables remains.
14th Jan 2020, 9:21 PM
Shadow
Shadow - avatar
+ 1
You might be able to test this by timestamping before and after using each method. Then comparing the two and seeing which (on average) takes longer. (If someone does not have a clear or consise answer).
14th Jan 2020, 9:19 PM
Pie
Pie - avatar