why to use QStringLiteral instead of QString



  • please look for follwing code

    //your code here
     void setupUi(QMainWindow *Analyzer)
        {
            if (Analyzer->objectName().isEmpty())
                Analyzer->setObjectName(QStringLiteral("Analyzer"));
    

    why we can't use Analyzer->setObjectName(QString("Analyzer"));
    or
    Analyzer->setObjectName("Analyzer");


  • Moderators

    @guru007 said in why to use QStringLiteral instead of QString:

    why we can't use Analyzer->setObjectName(QString("Analyzer"));
    or
    Analyzer->setObjectName("Analyzer");

    See the QString documentation at http://doc.qt.io/qt-5/qstring.html#more-efficient-string-construction :

    "Many strings are known at compile time. But the trivial constructor QString("Hello"), will copy the contents of the string, treating the contents as Latin-1. To avoid this one can use the QStringLiteral macro to directly create the required data at compile time. Constructing a QString out of the literal does then not cause any overhead at runtime."



  • A detailed explanation is also available here: https://woboq.com/blog/qstringliteral.html (oddly enough it's the result #1 on my Google for the qstringliteral query)



  • Thanks for ur replies....
    Is there any situation where we have to specifically used QStringliteral over to QString.


  • Qt Champions 2016

    @guru007
    Hi
    Its an optimization. You use QStringLiteral to avoid to constructing a QString and then copy data.
    So it can make a difference in loops where lots of strings are used and other cases with
    lots of access.
    For a small program, it won't really matter but why not just use in all cases where it fits.
    It won't hurt performance and there is no reason not to.

    I cant think of a case where you HAVE to use QStringliteral.



  • The only downside I found is that, being a macro, it breaks inline static code analysis in Visual Studio. Definitely a minor thing that should not stop you using it.

    The only case where it'd avoid it is if there is an explicit overload for const char* or QLatin1String. for example:

    QString base("base");
    base.prepend("prepended"); //better
    base.prepend(QStringLiteral("prepended")); //worse
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.