I am just curious. Let's say for example I need to output a number in the console.
The code would be:
#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());
}
Which would be better performance wise? I think the memory consumption is also different. QVariant(number).toString() would mean that it stores a QVariant in the stack. Not sure about QString::number(), shouldn't it just call the function(sure, the function has a QString return so it is allocated on the stack too and takes that space and that operations to allocated and unallocate it)? Anyway, sizeof() gives me 16 Bytes for QVariant and 4 Bytes for QString.
Of course the second variant is better.
QString::number()
is a static function that returns the desired string. When you use QVariant(number).toString();
you are first creating a QVariant
, and than converting it into a desired string, so you make an extra and unnecessary variable of QVariant
type.
Also, you don't need to transform the number to a string to output it with qDebug
. qDebug() << 42;
works fine.
Why not simply
qDebug << number
? If in case of a quint8
it outputs the character instead of the number itself, then just cast -
qDebug << static_cast<int>(number);
or (this one's a bit tricky to understand, look up integral promotions)
qDebug << +number;
I am betting that this option will be better (performance-wise) in comparison with either of your suggestions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With