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
7
  • 1
    What sort of string - std::string? and why do you care? Commented Oct 17, 2022 at 18:27
  • 1
    Why isn't 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. Commented Oct 17, 2022 at 18:27
  • @Jab that is not correct - std::string is probably the size of couple of pointers, ignoring small string optimisation. Commented Oct 17, 2022 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. Commented Oct 17, 2022 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? Commented Oct 17, 2022 at 18:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.