Lambda VS Function

20,210

Lambdas are an inplace way to create function objects. Function objects are usually used in places were in C one employs function pointers as callbacks.

One example could be C qsort function. To be able to sort an array of any type you have to give it the address of a function that will receive pointers to two elements of the array and return and integer indicating if the first is less (should be ordered before) than the second.:

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));

In the other side std::sort doesn't need a comparator function:

template <class RandomAccessIterator>
  void sort (RandomAccessIterator first, RandomAccessIterator last);

but if you need to pass one to specify a different order you can do it by passing a function object:

template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

You can create that function object using a lambda:

sort(v.begin(),
     v.end(),
     [](int a, int b){ return a > b; }
);

The intended uses of lambdas, function objects and function pointers are to pass as parameters to algorithms, as callbacks to get notified when something happens and similar cases.

To divide the code in meaningful named pieces you split it in well defined functions. To pass a function as a parameter to other functions a function object is a great way to do. If the function object is very small, it's only used once or you see no benefit in giving it a name, you can write your function object as a lambda.

Your question was about performance. Function objects (and lambdas) compares to function pointers. They can perform much faster.

If you look at qsort it will receive the address of a function and it will do a function call each time it has to compare. There is no way to inline because qsort and your function are compiled separately.

In std::sort example the lambda code is available at compile time and if it's simple enough the compiler will choose to inline and avoid all functions calls.

Yesterday at isocpp.org linked to a wonderful blog post titled Demystifying C++ lambdas that I strongly recommend.

Share:
20,210
Levi
Author by

Levi

I am a hobbyist programmer from New Zealand. Give me my badge.

Updated on August 27, 2020

Comments

  • Levi
    Levi over 3 years

    I just finished learning about lambda expressions and was wondering whether an expression or a regular function would execute faster when printing to a console using cout.

    Should I use

    // Lambda expression
    auto helloWorld = []()
    {
        cout << "Hello World" << endl;
    };
    

    or

    // Normal function
    void helloWorld()
    {
        cout << "Hello World" << endl;
    }
    

    Note: I am still a novice programmer, so do feel free to point out any errors I may have made. I can only learn

    Thanks