"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why are Lambdas More Optimizable than Plain Functions in C++?

Why are Lambdas More Optimizable than Plain Functions in C++?

Published on 2024-11-16
Browse:558

Why are Lambdas More Optimizable than Plain Functions in C  ?

Why Lambdas Allow for Enhanced Compiler Optimization Compared to Plain Functions

The C Standard Library (Second Edition) by Nicolai Josuttis asserts that lambdas can be optimized more effectively by compilers in comparison to plain functions. This advantage stems from the nature of lambdas as function objects.

When a lambda is passed to a function template, it is instantiated as a new function specifically tailored to that object. This allows the compiler to effortlessly inline the lambda call. Conversely, with plain functions, a function pointer is passed to the function template. Traditionally, compilers have faced difficulties inlining calls made through function pointers.

To illustrate this concept, consider the following function template:

template 
void map(Iter begin, Iter end, F f) {
    for (; begin != end;   begin)
        *begin = f(*begin);
}

Invoking this function with a lambda:

int a[] = { 1, 2, 3, 4 };
map(begin(a), end(a), [](int n) { return n * 2; });

results in an instantiation created by the compiler:

template 
void map(int* begin, int* end, _some_lambda_type f) {
    for (; begin != end;   begin)
        *begin = f.operator()(*begin);
}

In this case, the compiler has access to _some_lambda_type::operator() and can seamlessly inline calls to it. Each lambda has a distinct type, so using a different lambda with map() would produce a new instantiation.

However, if a function pointer were used instead:

map(int* begin, int* end, int (*f)(int)) {
    for (; begin != end;   begin)
        *begin = f(*begin);
}

The compiler would be unable to inline calls to f until the encompassing call to map() is also inlined, allowing it to pinpoint a specific function. This highlights the advantage of lambdas over plain functions in terms of compiler optimization.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3