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.
Bonus: Lambdas Compile 6.6x Faster than std::bind See here and Join C++ Stories Premium: Lambda can be 6.6x faster to compile than std::bind!. You can also read it in the book: C++ Lambda Story @Leanpub.
You can't declare the lambda expression static.
You can, in C++14 and higher. However, a lambda can only capture automatic variables, and a static variable, by definition, is not automatic. You don't need to capture static variables as they always have the same address in memory.
A lambda is generally cheap. here, lambda is just an instance of an anonymous type. The type itself is processed at compile-time, so no worries.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With