Reputation: 4938
I have a simple QT code that is called very often. It has to process some data and then format it into a QString
that is sen sent to a QwtText
object. Right now the function every time creates a QString
object with all the dynamic memory allocation work. Then this object is destroyed and memory deallocated after the function is done.
I'm trying to optimize the code by creating a local class QString
variable that would hold this formatted string. The idea is to prevent repeated malloc/free
calls. However, right after the first string assignment it appears that the QString
object frees and allocates the memory again, judging by the number returned by int QString::capacity()
link.
m_valuesLabelText.clear();
// Capacity is 1011
m_valuesLabelText += "<table width=50>";
// Capacity is 16
Is there any way to prevent this re-allocation and convince QString
to reuse the old buffer?
Thank you.
Upvotes: 1
Views: 584
Reputation: 3657
QString & oftenCalledFunction(BS *bs, QString &p)
{
p += "assignNew";
}
void func()
{
QString p(MAX_SIZE); //set MAX_SIZE appropriately.
BS bs;
p = oftenCalledFunction(&bs, p);
}
This way you allocate on stack, avoiding malloc calls. Does this help? Malloc is not very bad though, it doesnt straightaway release the memory back to the system. Most free store library internally implement some kind of pool allocation strategy.
Upvotes: 0
Reputation:
QString::clear
deallocates, as you can see by reading the source, e.g. here.
QString::resize
does not deallocate, so it can be a solution to your problem: yourString.resize(0)
.
Use QString::reserve
to allocate a suitable buffer.
Upvotes: 2