An std::function heap allocates and captures variables

If a lambda function with captured variables/references is assigned to a std::function, the std::function will, in most cases, allocate space on the heap to store the captured variables (note that some implementations of std::function do not heap-allocate if the size of the captured variable is less than a specific threshold).

This means that not only is there a slight performance penalty due to heap allocation and the execution of std::function but also that it is slower, as heap allocation implies cache misses (more about cache misses in Chapter 4, Data Structures).

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.