Use QString::fromLatin1() less to avoid string allocations

QString::fromLatin1 always allocates memory, but there are
cases where we can avoid/reduce allocations or/and reduce
text size, e.g.:

QStringBuilder expressions
Fix: replace QString::fromLatin1 with QL1S

QString::fromLatin1().arg(String) pattern
Fix: replace with QStringBuilder

Overloaded functions with QL1S arg
Fix: replace QString::fromLatin1 with QL1S

In rare cases if there is no overloaded function
with QL1S and we have deal with string literal,
replace QString::fromLatin1 with QStringLiteral.

Change-Id: Iabe1a3cc0830f40ef78a0548afa4368583c31def
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
This commit is contained in:
Anton Kudryavtsev 2016-08-18 11:57:26 +03:00
parent 251d6094ab
commit 6aa935cd92
18 changed files with 31 additions and 29 deletions

View File

@ -572,10 +572,9 @@ void QMimeBinaryProvider::loadMimeTypePrivate(QMimeTypePrivate &data)
const QString file = data.name + QLatin1String(".xml");
// shared-mime-info since 1.3 lowercases the xml files
QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString::fromLatin1("mime/") + file.toLower());
if (mimeFiles.isEmpty()) {
mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString::fromLatin1("mime/") + file); // pre-1.3
}
QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + file.toLower());
if (mimeFiles.isEmpty())
mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + file); // pre-1.3
if (mimeFiles.isEmpty()) {
qWarning() << "No file found for" << file << ", even though update-mime-info said it would exist.\n"
"Either it was just removed, or the directory doesn't have executable permission..."
@ -807,7 +806,7 @@ bool QMimeXMLProvider::load(const QString &fileName, QString *errorMessage)
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
if (errorMessage)
*errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString());
*errorMessage = QLatin1String("Cannot open ") + fileName + QLatin1String(": ") + file.errorString();
return false;
}

View File

@ -116,8 +116,7 @@ static QString generateSubObjectXml(QObject *object)
for ( ; it != end; ++it) {
QString name = (*it)->objectName();
if (!name.isEmpty() && QDBusUtil::isValidPartOfObjectPath(name))
retval += QString::fromLatin1(" <node name=\"%1\"/>\n")
.arg(name);
retval += QLatin1String(" <node name=\"") + name + QLatin1String("\"/>\n");
}
return retval;
}
@ -192,8 +191,7 @@ QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node
node.children.constEnd();
for ( ; it != end; ++it)
if (it->obj || !it->children.isEmpty())
xml_data += QString::fromLatin1(" <node name=\"%1\"/>\n")
.arg(it->name);
xml_data += QLatin1String(" <node name=\"") + it->name + QLatin1String("\"/>\n");
}
xml_data += QLatin1String("</node>\n");

View File

@ -569,7 +569,7 @@ bool QImageReaderPrivate::initHandler()
do {
file->setFileName(fileName + QLatin1Char('.')
+ QString::fromLatin1(extensions.at(currentExtension++).constData()));
+ QLatin1String(extensions.at(currentExtension++).constData()));
file->open(QIODevice::ReadOnly);
} while (!file->isOpen() && currentExtension < extensions.size());

View File

@ -1211,9 +1211,13 @@ QString QKeySequence::encodeString(int key)
static inline void addKey(QString &str, const QString &theKey, QKeySequence::SequenceFormat format)
{
if (!str.isEmpty())
str += (format == QKeySequence::NativeText) ? QCoreApplication::translate("QShortcut", "+")
: QString::fromLatin1("+");
if (!str.isEmpty()) {
if (format == QKeySequence::NativeText)
str += QCoreApplication::translate("QShortcut", "+");
else
str += QLatin1Char('+');
}
str += theKey;
}

View File

@ -2439,7 +2439,7 @@ int QFontDatabasePrivate::addAppFont(const QByteArray &fontData, const QString &
}
if (font.fileName.isEmpty() && !fontData.isEmpty())
font.fileName = QString::fromLatin1(":qmemoryfonts/") + QString::number(i);
font.fileName = QLatin1String(":qmemoryfonts/") + QString::number(i);
registerFont(&font);
if (font.families.isEmpty())

View File

@ -63,7 +63,7 @@ QT_BEGIN_NAMESPACE
static QString pixelToPoint(qreal pixels)
{
// we hardcode 96 DPI, we do the same in the ODF importer to have a perfect roundtrip.
return QString::number(pixels * 72 / 96) + QString::fromLatin1("pt");
return QString::number(pixels * 72 / 96) + QLatin1String("pt");
}
// strategies

View File

@ -319,9 +319,9 @@ void QHttpNetworkConnectionPrivate::prepareRequest(HttpMessagePair &messagePair)
if (systemLocale == QLatin1String("C"))
acceptLanguage = QString::fromLatin1("en,*");
else if (systemLocale.startsWith(QLatin1String("en-")))
acceptLanguage = QString::fromLatin1("%1,*").arg(systemLocale);
acceptLanguage = systemLocale + QLatin1String(",*");
else
acceptLanguage = QString::fromLatin1("%1,en,*").arg(systemLocale);
acceptLanguage = systemLocale + QLatin1String(",en,*");
request.setHeaderField("Accept-Language", acceptLanguage.toLatin1());
}

View File

@ -488,7 +488,7 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
interfaces = createInterfaces(interfaceListing);
for (ifaddrs *ptr = interfaceListing; ptr; ptr = ptr->ifa_next) {
// Find the interface
QString name = QString::fromLatin1(ptr->ifa_name);
QLatin1String name(ptr->ifa_name);
QNetworkInterfacePrivate *iface = 0;
QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin();
for ( ; if_it != interfaces.end(); ++if_it)

View File

@ -79,7 +79,7 @@ static bool ignoreProxyFor(const QNetworkProxyQuery &query)
if (!peerHostName.startsWith('.'))
peerHostName.prepend('.');
if (peerHostName.endsWith(QString::fromLatin1(token)))
if (peerHostName.endsWith(QLatin1String(token)))
return true;
}

View File

@ -135,7 +135,7 @@ bool QDeviceDiscoveryStatic::checkDeviceType(const QString &device)
qCDebug(lcDD) << "doing static device discovery for " << device;
if ((m_types & Device_DRM) && device.contains(QString::fromLatin1(QT_DRM_DEVICE_PREFIX))) {
if ((m_types & Device_DRM) && device.contains(QLatin1String(QT_DRM_DEVICE_PREFIX))) {
QT_CLOSE(fd);
return true;
}

View File

@ -91,7 +91,7 @@ QMimeData *QHaikuClipboard::mimeData(QClipboard::Mode mode)
const status_t status = clipboard->FindData(name, B_MIME_TYPE, &data, &dataLen);
if (dataLen && (status == B_OK)) {
const QString format = QString::fromLatin1(name);
const QLatin1String format(name);
if (format == QLatin1String("text/plain")) {
m_systemMimeData->setText(QString::fromLocal8Bit(reinterpret_cast<const char*>(data), dataLen));
} else if (format == QLatin1String("text/html")) {

View File

@ -173,7 +173,7 @@ QVariant QXcbMime::mimeConvertToFormat(QXcbConnection *connection, xcb_atom_t a,
// qDebug() << "mimeConvertDataToFormat" << format << atomName << data;
if (!encoding.isEmpty()
&& atomName == format + QLatin1String(";charset=") + QString::fromLatin1(encoding)) {
&& atomName == format + QLatin1String(";charset=") + QLatin1String(encoding)) {
#ifndef QT_NO_TEXTCODEC
if (requestedType == QVariant::String) {

View File

@ -1665,7 +1665,8 @@ QString QDB2Driver::formatValue(const QSqlField &field, bool trimStrings) const
}
case QVariant::ByteArray: {
QByteArray ba = field.value().toByteArray();
QString res = QString::fromLatin1("BLOB(X'");
QString res;
res += QLatin1String("BLOB(X'");
static const char hexchars[] = "0123456789abcdef";
for (int i = 0; i < ba.size(); ++i) {
uchar s = (uchar) ba[i];

View File

@ -334,7 +334,7 @@ void QPrintPreviewDialogPrivate::init(QPrinter *_printer)
QString caption = QCoreApplication::translate("QPrintPreviewDialog", "Print Preview");
if (!printer->docName().isEmpty())
caption += QString::fromLatin1(": ") + printer->docName();
caption += QLatin1String(": ") + printer->docName();
q->setWindowTitle(caption);
if (!printer->isValid()

View File

@ -830,7 +830,7 @@ QString QAccessibleTextWidget::attributes(int offset, int *startOffset, int *end
family = family.replace('=', QLatin1String("\\="));
family = family.replace(';', QLatin1String("\\;"));
family = family.replace('\"', QLatin1String("\\\""));
attrs["font-family"] = QString::fromLatin1("\"%1\"").arg(family);
attrs["font-family"] = QLatin1Char('"') + family + QLatin1Char('"');
}
int fontSize = int(charFormatFont.pointSize());

View File

@ -63,7 +63,7 @@ QT_BEGIN_NAMESPACE
*/
static QString qt_strippedText(QString s)
{
s.remove( QString::fromLatin1("...") );
s.remove(QStringLiteral("..."));
for (int i = 0; i < s.size(); ++i) {
if (s.at(i) == QLatin1Char('&'))
s.remove(i, 1);

View File

@ -188,8 +188,8 @@ static QString int2string(int num, int base, int ndigits, bool *oflow)
} while (n != 0);
len = ndigits - len;
if (len > 0)
s.fill(QLatin1Char(' '), len);
s += QString::fromLatin1(p);
s += QString(len, QLatin1Char(' '));
s += QLatin1String(p);
}
break;
}

View File

@ -415,7 +415,7 @@ QSize QPushButton::sizeHint() const
QString s(text());
bool empty = s.isEmpty();
if (empty)
s = QString::fromLatin1("XXXX");
s = QStringLiteral("XXXX");
QFontMetrics fm = fontMetrics();
QSize sz = fm.size(Qt::TextShowMnemonic, s);
if(!empty || !w)