Why Lambdas Outperform Functions in Compiler Optimization
In his book "The C Standard Library (Second Edition)," Nicolai Josuttis claims that lambdas enjoy superior compiler optimization compared to ordinary functions. This distinction stems from the nature of lambdas as function objects, allowing for function template instantiation tailored to specific lambda objects.
Inlining Advantage for Lambdas
Unlike plain functions, which pass function pointers to function templates, lambdas are passed as function objects. This triggers the creation of a new function tailored to the specific lambda object. As a result, the compiler can effortlessly inline the lambda call.
Function Pointer Hindrance
In contrast, functions are hindered by their passing mechanism in function templates. Compilers face challenges in inlining calls made through function pointers. While theoretical inlining is possible, it requires the inlining of the enclosing function as well.
Instantiation Example
Consider the function template "map" below:
template <typename Iter, typename F> void map(Iter begin, Iter end, F f) { for (; begin != end; ++begin) *begin = f(*begin); }
Invoking "map" with a lambda:
int a[] = { 1, 2, 3, 4 }; map(begin(a), end(a), [](int n) { return n * 2; });
Generates the following instantiation:
template <> void map<int*, _some_lambda_type>(int* begin, int* end, _some_lambda_type f) { for (; begin != end; ++begin) *begin = f.operator()(*begin); }
The compiler identifies the lambda's operator() and can effortlessly inline calls to it.
However, when "map" is called with a function pointer:
template <> void map<int*, int (*)(int)>(int* begin, int* end, int (*f)(int)) { for (; begin != end; ++begin) *begin = f(*begin); }
The function pointer "f" points to a different location for each invocation of "map," making it intractable for the compiler to inline "f" calls alone. Inlining requires the encompassing "map" call to be inlined as well, enabling the compiler to determine the specific function pointed to by "f."
The above is the detailed content of Why do Lambdas have an Inlining Advantage Over Functions in Compiler Optimization?. For more information, please follow other related articles on the PHP Chinese website!