I just tried to optimize some communication stack. I am using Qt 5.3.2 / VS2013.
The stack uses a QByteArray as a data buffer. I intended to use the capacity()
and reserve()
methods to reduce unnecessary internal buffer reallocations while the data size grows. However the behaviour of QByteArray turned out to be inconsistent. The reserved space sometimes seems to be squeezed implicitly.
I could extract the following demo applying a string append, a string assignment and a character append to three buffers. These single operations seem to preserve the internal buffers size (obtained using capacity()
). However when applying each of these three operations to the same QByteArray the reserved size changes. The behaviour looks random to me:
QByteArray x1; x1.reserve(1000);
x1.append("test");
qDebug() << "x1" << x1.capacity() << x1;
QByteArray x2; x2.reserve(1000);
x2 = "test";
qDebug() << "x2" << x2.capacity() << x2;
QByteArray x3; x3.reserve(1000);
x3.append('t');
qDebug() << "x3" << x3.capacity() << x3;
QByteArray x4; x4.reserve(1000);
x4.append("test");
x4.append('t');
x4 = "test";
qDebug() << "x4" << x4.capacity() << x4;
The expected output would be:
x1 1000 "test"
x2 1000 "test"
x3 1000 "t"
x4 1000 "test"
But the actual output is:
x1 1000 "test"
x2 1000 "test"
x3 1000 "t"
x4 4 "test"
Does anyone have an explanation for that strange behaviour?
UPDATE: Looks like clear()
also discards reservation.