Home > database >  How is that possible that these two pieces of code have the same memory usage?
How is that possible that these two pieces of code have the same memory usage?

Time:11-26

First case:

#include <vector>

int main() {
    const int iterations = 1'000'000;
    std::vector<const char *> c;
    for (int i = 0; i < iterations; i  ) {
        c.push_back("qwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiop");
    }
}

Second case:

#include <vector>

int main() {
    const int iterations = 1'000'000;
    std::vector<const char *> c;
    for (int i = 0; i < iterations; i  ) {
        c.push_back("qwerty");
    }
}

In both cases the shown memory usage of the active process is about 11 MB.

The first thought was that the memory usage refers only to the pointers size, but then how should i know from outside how much memory does a certain software uses? ( Without expliciting calculating the size from inside the code)

Edit: I thought that with c.push_back("qwerty") i was creating a new string every time. That was my objective. I managed to do it now by modifing the code in this way:

#include <vector>

int main() {
    const int iterations = 1'000'000;
    std::vector<const char *> c;
        for (int i = 0; i < iterations; i  ) {
            std::string* s = new std::string("sadadasd");
            c.push_back((*s).c_str());
    }
}

It looks awful but at least now the memory usage makes sense. Is there a more elegant way to achieve this?( I mean without introducing std::string and using only const char*)

CodePudding user response:

A pointer takes up (usually) 8 bytes.

In both cases you create a vector with a million identical pointers. So that's 8 million bytes for the vector data. Total memory usage depends on more things, like how much empty space is in the vector, and how much memory is used by the rest of the process.

Both programs only include one copy of the string. The extra 44 bytes are a drop in the bucket. The second program might not even use an extra 44 bytes, if they were unused padding bytes anyway - which is likely, since the OS can only allocate memory in 4096-byte chunks called pages.

  • Related