Home > Article > Backend Development > 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 <typename Iter, typename F> 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*, _some_lambda_type>(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*, int (*)(int)>(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.
The above is the detailed content of Why are Lambdas More Optimizable than Plain Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!