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.