QStringLiteral

QStringLiteral宏在编译时生成QString数据,避免运行时内存分配和转换开销,提高性能。尤其适用于已知字符串常量的情况。使用QStringLiteral可以减少不必要的资源消耗,例如在调用hasAttribute函数时,直接传递QStringLiteral能避免临时对象创建。
摘要由CSDN通过智能技术生成

The macro generates the data for a QString out of the string literal str at compile time. Creating a QString from it is free in this case, and the generated string data is stored in the read-only segment of the compiled object file。

使用QStringLiteral宏可以在编译期把代码里的常量字符串str直接构造为QString对象,于是运行时就不再需要额外的构造开销了。

如果编译器支持,则QStringLiteral宏在编译时从str生成一个QString的数据。在这种情况下从 QStringLiteral创建一个QString是自由的,生成的字符串数据存储在编译的目标文件的只读段中;对于不支持的编译器,QStringLiteral的使用效果将与使用QString::fromUtf8() 一样。

If you have code that looks like this:

// hasAttribute takes a QString argument
if (node.hasAttribute("http-contents-length")) //...

then a temporary QString will be created to be passed as the hasAttribute function parameter. This can be quite expensive, as it involves a memory allocation and the copy/conversion of the data into QString's internal encoding.

这将创建一个临时QString 作为hasAttribute函数的参数传递。这可能是非常耗费资源的,因为它涉及内存分配以及将数据复制和转换为QString的内部编码数据。

This cost can be avoided by using QStringLiteral instead:

if (node.hasAttribute(QStringLiteral(u"http-contents-length"))) //...

In this case, QString's internal data will be generated at compile time; no conversion or allocation will occur at runtime.

然后,QString 的内部数据将在编译时生成,并且在运行时将不会发生任何的转换或分配。

Using QStringLiteral instead of a double quoted plain C++ string literal can significantly speed up creation of QString instances from data known at compile time.

使用 QStringLiteral 而不是双引号的 ascii 文字可以大大加快从编译时已知的数据中创建 QString 的速度。如果编译器启用了 C++11,则字符串 str 实际上可以包含 unicode 数据。

Note: QLatin1String can still be more efficient than QStringLiteral when the string is passed to a function that has an overload taking QLatin1String and this overload avoids conversion to QString. For instance, QString::operator==() can compare to a QLatin1String directly:

注意:在有一些情况下 QLatin1String 是比 QStringLiteral 更有效的:如果它被传递给一个有直接接受 QLatin1String 而不转换成 QString 类型参数的重载的函数时。 例如,QString::operator == 就是这种情况

if (attribute.name() == QLatin1String("http-contents-length")) //...

Note: Some compilers have bugs encoding strings containing characters outside the US-ASCII character set. Make sure you prefix your string with u in those cases. It is optional otherwise.

//串联字符串文字不能与 QStringLiteral 一起使用。
QString s = QStringLiteral("a" "b");
//QStringLiteral 不能用来初始化 QString 的列表或数组。
QString a[] = { QStringLiteral("a"), QStringLiteral("b") };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值