Qt string builder in for loop

Stefano picture Stefano · Aug 29, 2012 · Viewed 8.6k times · Source

following this and this documentation I would use the QStringBuilder in a for loop. The code where I should apply it is

QStringList words;
QString testString;

for (auto it = words.constBegin(); it != words.constEnd(); ++it)
{
    testString += "[" + *it + "] ";
}

However I don't understand how I could write it to use the QStringBuilder as here I'm doing an assignment, instead the QStringBuilder requires me to use the % operator and do only one assignment following the docs.

Answer

PCaetano picture PCaetano · Aug 30, 2012

AFAICS here, QStringBuilder doesn't have an operator %=.

However, if you want to maintain your loop, you could try something like this:

#include <QStringBuilder>
#include <QStringList>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    QStringList words;
    words << "a1" << "a2" << "a3";
    QString testString;

    for (auto it = words.constBegin(); it != words.constEnd(); ++it)
    {
        testString = testString % *it % " ";
    }
    cout << testString.toStdString() << endl;
}

There's also mention of the QT_USE_QSTRINGBUILDER macro, which turns all + usage into %, provided that doesn't create problems elsewhere on your code.

EDIT:

In light of Marvin's comment, I believe I should add a few clarifications to my answer: This answer shows one way of explicitly using QStringBuilder and operator% in a loop. QStringBuilder was created to optimize concatenation expressions, and that optimization is achieved by eliminating the need for temporaries, and calculating the total size of the concatenated string and allocating it all at once (obviously, this can only be done at the "end" of the expression).

This means its optimal use is probably not in a loop (such as the code above). However, even then it gives you some sort of optimization, as can be seen both from the gprof and Measure-Command output for the two versions below.

Version 1 - QStringBuilder and operator% (gprof cumulative seconds: 0.46; PowerShell Measure-Command: 5:23s)

for (auto it = words.constBegin(); it != words.constEnd(); ++it)
{
    for (int i = 0; i < 100000; ++i)
    {
        testString = testString % *it % " ";
    }
}

Version 2 - Qstring and operator+ (gprof cumulative seconds: 0.61; PowerShell Measure-Command: 10:47s)

for (auto it = words.constBegin(); it != words.constEnd(); ++it)
{
    for (int i = 0; i < 100000; ++i)
    {
        testString = testString + *it + " ";
    }
}

So, I'd say that using QStringBuilder and operator% probably won't leave you noticeably worse (please note that the above values are a bit skewed, unless your app is actually performing thousands of concatenations with no I/O whatsoever). But, as usual, it's up to you to measure your execution times and decide what's working best for you.