Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which vector and map, uses less memory (large set of data and unknown size)

I wonder which container uses less memory between std::map and std::vector with a large set of data.

Loads of posts talk about efficiency, and my priority is not efficiency but memory consumption. So, if we don't know the number of our data (in my case can be over 12,000,000 entries, every entry is a string of 20 characters), is map really better than vector?

like image 280
Atouk Avatar asked Feb 10 '23 02:02

Atouk


1 Answers

A std::vector must organise the strings in contiguous memory. (The standard insists on that). So the amount of contiguous memory in your example will be at least sizeof(string) * 12,000,000 for a std::vector. Fortunately, each string probably has its buffer in the heap: 20 characters is around the cut-off for std::string implementations that use a fixed buffer for short strings.

std::map will not have this contiguity issue, so is probably a better container to use in this instance. But, overall, it will probably consume more memory. But that memory will be easier for the program to acquire.

like image 58
Bathsheba Avatar answered Feb 13 '23 02:02

Bathsheba