Hacker News new | past | comments | ask | show | jobs | submit login

Fully agree with what you're saying. Just a nitpick about bind (which I'm sure you're aware of, just for the sake of others).

The return type of {boost,std}::bind is unspecified (it's basically just a "callable"). This means that bind doesn't have to do type erasure. On the other hand, {boost,std}::function has to do type erasure, which can boil down to a virtual function call. But that's orthogonal to where the callable came from.

Another thing to keep in mind is that if you're writing a function like `copy_if` which takes a callback, but doesn't have to store it for later use, it's much better to take the callback as a template type rather than going through the type-erasing {boost,std}::function. Doing the latter makes the compiler's job a lot harder.




It's not type erasure per se, but it's somewhat functionally equivalent. When you pass a function pointer (or pointer to member function) to bind(), it has to store that pointer in a member variable and perform an indirect call in operator(). In theory this is something that a compiler should be able to optimize away, but in practice they very rarely actually do, so using bind() as the argument for a STL algorithm typically does not result in the whole thing getting inlined out of existence. Lambdas, OTOH, are super easy to inline out of existence and compilers actually do so most of the time.


Note that I'm not advocating bind over lambda. I'm saying that one shouldn't expect a boost in performance when switching from std::bind to lambda. Switching from std::function to a templatized "Callable" could give a boost in performance, but like I said, that's orthogonal to how the callable was created.

There really is quite a difference between what std::bind returns and a type-erasing class like std::function. For the latter, the type erasure may result in a virtual call that the optimizer has a hard time seeing through.

In practice, compilers are pretty good at optimizing bind. Here are some examples where lambda and bind generate identical code: https://godbolt.org/g/dQCSeG




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: