Qt: which is better for converting a number to QString, QVariant or QString :: number

I'm just curious. Say, for example, I need to display the number in the console.

The code:

#include <QDebug> #include <QVariant> #include <QString> void displayNumber(quint8 number) { qDebug() << QVariant(number).toString(); qDebug() << QString::number(number); //or for example // QLabel label; // label.setText(QString::number(number)); //or // label.setText(QVariant(number).toString()); } 

What would be better? I think the memory consumption is also different. QVariant (number) .toString () means that it stores QVariant on the stack. Not sure about QString :: number (), shouldn't it just call the function (of course, the function returns a QString so that it also gets allocated on the stack and occupies this space and that the operations are allocated and not allocated)? Anyway, sizeof () gives me 16 bytes for QVariant and 4 bytes for QString.

+6
source share
2 answers

Of course, the second option is better.

QString::number() is a static function that returns the desired string. When you use QVariant(number).toString(); , you first create a QVariant , and then convert it to the desired string, so you make an additional and unnecessary variable of type QVariant .

In addition, you do not need to convert the number to a string to display it with qDebug . qDebug() << 42; works great.

+4
source

Why not just

 qDebug << number 

? If in case of quint8 it displays a character instead of the number itself, then just press -

 qDebug << static_cast<int>(number); 

or (it's a little hard to see, see integrated promotions)

 qDebug << +number; 

I am sure that this option will be better (in performance) compared to any of your suggestions.

+1
source

All Articles