Unsolved Conversion question
I have a large (megabytes) string in a QJsonValue, that I need to convert to QByteArray, as I am sending the string as data with a QNetworkRequest.
Currently I am doing this:
^^Would this incur copying the same data to memory many times for some reason? If so, how would you go about implementing this without unnecessary copyings?
Qt stores QString as a 16-bit unicode string. When you call toUtf8(), you're not only converting it to a QByteArray, but also converting its encoding. So data must be copied and you can't avoid the increase in memory usage.
Thanks, great to know. Do you think that with the particular expression here, data would be copied once or twice? Just curious. I would presume and hope that it can be converted to QString from QJsonValue with no cost, is this true?
Also it is curious that you say that the data needs to be re-encoded. I have been in the understanding that utf-8 is somewhat the standard internal encoding in Qt and QML, is this not true?
kshegunov Moderators last edited by
I have been in the understanding that utf-8 is somewhat the standard internal encoding in Qt and QML, is this not true?
Qt uses UTF-16 internally.
Source code files are utf8 encoded, but QString itself uses 16bit unicode.
QJsonValue holds a reference to the string data, so no copy needs to be done by toString().
Also for anyone interested, I asked the same question at StackOverflow, and it was suggested that I use QJsonDocument for such operations, which is probably good advice:
I simply needed the QByteArray, I had no idea that toUtf8() had this overhead. QJsonDocument seems to be able to convert straight to QByteArray with QByteArray QJsonDocument::toBinaryData() const
I do have one extra question: Do you know if it would incur any extra cost to use the QJsonDocument constructor, giving it a large QJsonObject as parameter?