0

What is the expected memory usage of a vector of a struct, that contains a string (let's say on average 5 bytes), an int (4 bytes) and a double (8 bytes).

Would each entry just take 17 bytes or are there other things to consider?

struct Entry {
  int entry1;
  string myString; // on average 5 characters
  double value;
}

vector<Entry> dataframe
Nickpick
  • 6,163
  • 16
  • 65
  • 116
  • 1
    What sort of string - std::string? and why do you care? – Neil Butterworth Oct 17 '22 at 18:27
  • 1
    [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) and possibly a lot more to consider, depending on the actual struct and whether you are also interested in internal `std::vector` implementation. Also, "on average" suggests that you think there is some possibility for variance in struct size, there is none. `sizeof()` is a compile-time constant. – Yksisarvinen Oct 17 '22 at 18:27
  • @Jab that is not correct - std::string is probably the size of couple of pointers, ignoring small string optimisation. – Neil Butterworth Oct 17 '22 at 18:30
  • A couple pointers and maybe some space for Short String Optimization. And the asker's probably interested in summing up the storage the pointer's pointing at, if any. – user4581301 Oct 17 '22 at 18:33
  • Are you interested in the size of the string object, or the size of the data being held by the string? Do you care about the implicit terminator the string manages? Do you care about intra-padding and inter-padding bytes? What does `sizeof(Entry)` give you? – Eljay Oct 17 '22 at 18:34
  • also, each element in vector must have the same size – Neil Butterworth Oct 17 '22 at 18:34
  • @NeilButterworth you're right, I deleted my comment. – Jabberwocky Oct 18 '22 at 18:05

1 Answers1

1

You're going to use at least sizeof(std::vector<Entry>) + N * sizeof(Entry) bytes, and short string optimization means that if all of your strings are short you'll probably use exactly that much.

How much memory that is will depend on your compiler, standard library implementation, and architecture. Assuming you're compiling for x86_64, sizeof(Entry) will likely be either 40 or 48 bytes (MSCRT and libstdc++ have 32 byte std::strings, libc++ uses 24 byte std::strings). sizeof(std::vector<Entry>) is likely 24 bytes. That brings total memory usage up to a likely 24 + N * 48 bytes.

If your strings are longer than about 15 characters then std::string will have to store the actual character data in an external allocation. That can add an arbitrary extra amount of memory usage.


Note that this is just the memory directly used to store your objects. The memory allocator may allocate memory from the system in larger chunks, and there's also some overhead used for tracking what memory is allocated and what is available.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52