Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: Which is better for transforming a number to QString, QVariant or QString::number

Tags:

c++

qt

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.

like image 401
Lilian A. Moraru Avatar asked Nov 08 '12 10:11

Lilian A. Moraru


2 Answers

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.

like image 191
SingerOfTheFall Avatar answered Sep 30 '22 16:09

SingerOfTheFall


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.

like image 31
Armen Tsirunyan Avatar answered Sep 30 '22 17:09

Armen Tsirunyan