7 ms·
About 23 minutes in, Mr. Blow says that lambdas has "questionable performance," but the actual cost is relatively predictable. Current C++ compilers will try t
by implicit 12y ago
About 23 minutes in, Mr. Blow says that lambdas has "questionable performance," but the actual cost is relatively predictable.
Current C++ compilers will try to inline lambdas. Mr. Blow's specific example will be inlined by both g++ and clang, (I haven't tested MSVC) depending on the optimization level you set.
std::function does introduce overhead, and the reason why is important:
How can you implement an array of lambdas that all accept the same signature, but close over different kinds of environments? You need to be able to copy and destruct those environments without static knowledge of how big they are and what's in them.
std::function makes this work by allocating the environment on the heap and hiding it from the type signature. If you are averse to this extra overhead, there's a really easy rule to follow: Until you actually explicitly write "std::function" in your code, you do not pay its cost.
I know a few ways around this:
If you always use auto when dealing with function-local lambdas, you don't pay any extra overhead. You can think of each lambda as being the sole instance of a struct that contains the environment to be closed over, plus a non-virtual method. Just be aware that no lambda is type-compatible with any other. (exception: two lambdas are type-compatible if they have empty environments and the same type signature)
You can templatize lambda-consuming functions over the type of the lambda. This can work out really well if you pay attention to how function inlining happens, as the compiler can not only inline the template function, but the lambda as well. You can generally assume that the compiler is capable of fully inlining maps and folds.
Lastly, if your lambda doesn't close over anything, you can cast it as a C-style function pointer.