Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead to using std::vector?

I know that manual dynamic memory allocation is a bad idea in general, but is it sometimes a better solution than using, say, std::vector?

To give a crude example, if I had to store an array of n integers, where n <= 16, say. I could implement it using

int* data = new int[n]; //assuming n is set beforehand

or using a vector:

std::vector<int> data;

Is it absolutely always a better idea to use a std::vector or could there be practical situations where manually allocating the dynamic memory would be a better idea, to increase efficiency?

like image 426
Vivek Ghaisas Avatar asked Mar 08 '13 12:03

Vivek Ghaisas


People also ask

How much space does a vector take up C++?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements. It is very efficient. However, both std::set and std::unordered_set use nearly an order of magnitude more memory than would be strictly necessary.

Is std::vector fast?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

Is std::vector on heap or stack?

std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.

Does std::vector use dynamic allocation?

std::vector lives in the <vector> header. Note that in both the uninitialized and initialized case, you do not need to include the array length at compile time. This is because std::vector will dynamically allocate memory for its contents as requested.


1 Answers

It is always better to use std::vector/std::array, at least until you can conclusively prove (through profiling) that the T* a = new T[100]; solution is considerably faster in your specific situation. This is unlikely to happen: vector/array is an extremely thin layer around a plain old array. There is some overhead to bounds checking with vector::at, but you can circumvent that by using operator[].

like image 144
us2012 Avatar answered Sep 29 '22 07:09

us2012