Memory footprint of 5 byte QByteArray. Is quint64 or QByteArray of 5 bytes more efficient for storage?

StackOverflow https://stackoverflow.com/questions/17677362

  •  03-06-2022
  •  | 
  •  

Question

Checking size of QByteArray always returns 4 bytes, I'm assuming due to implicit sharing of data in Qt:

int n = 50; //or n = 100, 200
QByteArray arr(n,'a');
cout << sizeof(arr) << endl;
::getchar();

Always prints 4

How can I estimate the actual memory footprint of QByteArray? The question is motivated by efficiently storing large number of 5 byte identifiers - they can either be stored each as quint64 (using 8 bytes for each, 3 bytes are therefore wasted), or as each as QByteArray - but I'm not sure how to estimate overhead in the latter case....

I would like to use these identifiers as key for QMap, so they should each be in their own structure - one long QByteArray won't work...

Was it helpful?

Solution

The actual data for QByteArray (in Qt 4.8) can be found in qbytearray.h and looks like this:

struct Data {
    QBasicAtomicInt ref;
    int alloc, size;
    char *data;
    char array[1];
};

So a quint64 will use less storage if your data fits into it.

OTHER TIPS

sizeof(arr) shows you the pointer size of the object. do arr.squeeze(); then arr.capacity();

But dont keep the squeeze call for final code, what it does is gets rid of any prealocated unused memory by the object, so it reallocates and memcopies (expensive).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top