Home >Backend Development >C++ >Why Do Compilers Optimize Lambdas Better Than Plain Functions?

Why Do Compilers Optimize Lambdas Better Than Plain Functions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 02:20:09113browse

Why Do Compilers Optimize Lambdas Better Than Plain Functions?

Lambda Function Optimization

Nicolai Josuttis claims in "The C Standard Library" that compilers optimize lambdas better than plain functions. This raises the question of why this is the case.

Inline Optimization

One might assume that inline optimization wouldn't differentiate between lambdas and plain functions. However, the key difference lies in the nature of lambdas as function objects.

Function Objects vs. Function Pointers

When a lambda is passed to a function template, it creates a new function specifically for that object, resulting in a trivially inlinable function call. In contrast, plain functions pass function pointers, which typically cause problems for inline optimization. Compilers can theoretically inline such calls, but only if the surrounding function is also inlined.

Example

Consider a function template map that takes an iterator and a function object as parameters:

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

Invoking this template with a lambda:

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

Creates a new instantiation of the function:

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 can readily inline calls to the lambda's operator().

However, when using a function pointer:

int a[] = { 1, 2, 3, 4 };
map(begin(a), end(a), &my_function);

The resulting instantiation becomes:

template <>
void map<int*, int (*)(int)>(int* begin, int* end, int (*f)(int)) {
    for (; begin != end; ++begin)
        *begin = f(*begin);
}

Here, f points to a different address for each call to map, prohibiting inline optimization unless the surrounding call to map is also inlined.

Thus, the optimization advantage of lambdas stems from their ability to create function objects that enable trivial inline capabilities.

The above is the detailed content of Why Do Compilers Optimize Lambdas Better Than Plain Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn