Skip to content

Instantly share code, notes, and snippets.

@NIA
Last active August 29, 2015 14:00
Show Gist options
  • Save NIA/25560a3580e3872557a9 to your computer and use it in GitHub Desktop.
Save NIA/25560a3580e3872557a9 to your computer and use it in GitHub Desktop.
Draft of suggested edit to answer (http://stackoverflow.com/a/23444489/693538)

You can try with QByteArray that shares same QString's interface but is more suitable for performance issues.I obtain 36 ms (qt 5.2 clang) vs. your original 57 ms (on my machine) with this code:

QByteArray allDatab;
foreach(const int & value, values) {
    allDatab += QByteArray::number(value);
    allDatab += '\n';
}
QString result(allDatab);

and 29 ms with this version (that maybe confirm your assumptions about setNum):

QByteArray allDatad;
QByteArray number;                       
foreach(const int & value, values) {
    number.setNum(value);             
    allDatad += number;
    allDatad += '\n';
}

But why did the same trick (setNum) not work with QString? The answer is easy if we look into sources.

QString::setNum body source (src/corelib/tools/qstring.cpp:6410):

*this = QLocaleData::c()->longLongToString(n, -1, base);
return *this;

As you see, the need to be locale-aware requires this function to always create (and allocate) new string! Not reallocate, but namely allocate a new one. Just to assing it to self then.

Nothing like this is needed for QByte array. The same setNum function has nothing about locale: it has a static array and makes hardcore formatting into it.

QByteArray::setNum body source (src/corelib/tools/qbytearray.cpp:3691):

const int buffsize = 66; // big enough for MAX_ULLONG in base 2
char buff[buffsize];
char *p;

/* MAGIC GOES HERE -- deleted here for shortness */

clear();
append(p, buffsize - (p - buff));
return *this;

As you see, we first work inside of static array buffer, then clear byte array and call append. All these operations will not cause neiter alloc, nor realloc if the bytearray was initially big enogh.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment