fm_cpp
fm_cpp

Reputation: 61

c++ static lambda performance

I stumbled upon this code that is using c++ lambda:

qreal defaultDpiScale()
{
    static qreal scale = []() {
        if (const QScreen *screen = QGuiApplication::primaryScreen())
            return screen->logicalDotsPerInchX() / 96.0;
        return 1.0;
    }();
    return scale;
}

Why would anyone write this function using lambda vs. something like this:

qreal defaultDpiScale()
{
    if (const QScreen *screen = QGuiApplication::primaryScreen())
        return screen->logicalDotsPerInchX() / 96.0;
    else
        return 1.0;
}

Is there any performance advantage? I'm just trying to understand the usefulness of lambda in this context.

Upvotes: 6

Views: 767

Answers (1)

Daniel Jour
Daniel Jour

Reputation: 16156

qreal defaultDpiScale()
{
 // vvvv
    static qreal scale = []() {
        if (const QScreen *screen = QGuiApplication::primaryScreen())
            return screen->logicalDotsPerInchX() / 96.0;
        return 1.0;
    }();
    return scale;
}

scale is a static local variable. As such, its initialization expression is executed only once. Since the initialisation is a bit more complex, the author uses a directly called lambda in order to have more freedom (like declaring variables).

A named function would have been the alternative, but for that you need a descriptive name (initDefaultDpiScale?) that pollutes the namespace, have more code to write which is then not even in one place, but scattered over two functions.

Your code executes an if and (up to) 3 function calls every time the function is called. Depending on how complex these functions are this could have an enormous impact on performance. Further, if one of the functions has a side effect, then your code even changes the behavior of the function (as visible to the rest of the code).

Finally note the different intention that gets carried across by your code: The scale is something that depends on a possibly varying runtime environment. The original code instead states that scale depends on the runtime environment, but can be considered constant for the entire runtime of the program.

Upvotes: 3

Related Questions