C ++ static lambda performance

I came across this code that uses 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 a lambda against something like this:

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

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

+5
source share
1 answer
 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 local static variable. Thus, its initialization expression is executed only once. Since initialization is a bit more complicated, the author uses the directly called lambda for more freedom (e.g. variable declarations).

A named function would be an alternative, but for this you need a descriptive name ( initDefaultDpiScale ?), Which pollutes the namespace, has more code for writing, which is then not even in one place, but scattered across two functions.

Each time a function is called, your code executes if and (up to) 3 functions. Depending on how complex these features are, this can have a huge impact on performance. Also, if one of the functions has a side effect, then your code even changes the behavior of the function (as you can see for the rest of the code).

Finally, pay attention to the different intent that your code carries: scale is something that depends on a possibly changing runtime. Instead, the source code indicates that scale depends on the runtime, but can be considered a constant for the entire execution time of the program.

+2
source

Source: https://habr.com/ru/post/1268729/


All Articles