What is the best way to initialize QString
:
QString name = "name";
// or
QString nameL = QStringLiteral("name");
// or
QString nameLL = QLatin1String("name");
// or something else...
What is the best way to initialize QString
:
QString name = "name";
// or
QString nameL = QStringLiteral("name");
// or
QString nameLL = QLatin1String("name");
// or something else...
QStringLiteral
will have the lowest runtime overhead. It is one of the few literal QString
initializations with O(1) cost. QLatin1String
will be pretty fast, but have O(N) cost in length of the string. The intiialization with C string literal will have the highest O(N) cost and is equivalent to IIRC QString::fromUtf8("…")
. The 2nd and 3rd initialization also adds an O(N) memory cost, since a copy of the string is made (!). Whatever “savings” you made in executable size thus promptly vanish as the program starts up :(
Initialization via QStringLiteral
wins, although you may want to leverage modern C++11 custom literals to make it shorter. Resist the urge to use a macro for it: it’d be an extremely misguided approach as you pollute the global namespace with a short symbol.