7

What is the best way to initialize QString:

   QString name = "name";
   // or
   QString nameL = QStringLiteral("name");
   // or
   QString nameLL = QLatin1String("name");
   // or something else...
svadym
  • 167
  • 1
  • 10
  • 2
    Good writeup: [QStringLiteral explained](https://woboq.com/blog/qstringliteral.html) – Swordfish Nov 13 '18 at 11:59
  • @Swordfish Thanks for the link, interesting article. – svadym Nov 13 '18 at 12:05
  • 2
    Generally speaking: If you want to initialize a `QString` from a char*, use `QStringLiteral`. If you want to pass it to a method, check if that method has an overload for `QLatin1String` - if yes you can use that one, otherwise fall back to `QStringLiteral`. The only exception for both cases is an empty string - simply use `QString()`. – Felix Nov 13 '18 at 12:06

1 Answers1

7

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.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313