6

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.

4

2 回答 2

4

当然,第二种变体更好。

QString::number()是一个返回所需字符串的静态函数。当您使用时,QVariant(number).toString();您首先创建一个QVariant, 然后将其转换为所需的字符串,因此您创建了一个额外且不必要的QVariant类型变量。

此外,您无需将数字转换为字符串即可使用qDebug. qDebug() << 42;工作正常。

于 2012-11-08T10:56:08.433 回答
1

为什么不简单

qDebug << number

? 如果在 a 的情况下quint8它输出字符而不是数字本身,那么只需转换 -

qDebug << static_cast<int>(number);

或者(这个有点难理解,查积分促销)

qDebug << +number;

我敢打赌,与您的任何一个建议相比,这个选项会更好(性能方面)。

于 2012-11-08T10:54:42.150 回答