0

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...

Ilya Kobelevskiy
  • 5,245
  • 4
  • 24
  • 41
  • If you want to store those 5 bytes efficiently, then how about plain old structs? –  Jul 16 '13 at 13:30
  • @Roku and how would I store them as POD - struct containing char[5] with comparison operator? – Ilya Kobelevskiy Jul 16 '13 at 13:44
  • Maybe using structs is not a good idea, at least using QByteArray is easier. By the way, how many of those 5 byte identifiers do you have? More than 200? –  Jul 16 '13 at 14:20
  • @Roku Yes, thousands of them - 1000 to 4000 per file, goal is to prcess as much files as possible at once (up to 800-900 files). Why, what is special about 200? – Ilya Kobelevskiy Jul 16 '13 at 14:54
  • Oh, there is nothing special about 200, it just came out of your code. I think that amount of identifiers is not much at all. If you use quint64's, you will have 900*4000*3=11 megabytes of wasted memory. Unless your program is already using gigabytes of memory (and having problems with some 32-bit OS), I wouldn't be concerned about that amount of wasted memory. Instead, I would choose the method that is easiest to implement and maintain. –  Jul 16 '13 at 15:19

2 Answers2

1

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).

madnut
  • 124
  • 5
1

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.

Dan Milburn
  • 5,600
  • 1
  • 25
  • 18