Are there any performance impacts (positive or negative) when binding functions (using Boost Bind) ?
Maybe, may not be. It depends.
The result of std::bind
(or also boost::bind
) is a so-called "bind expression", which has an unknowable type determined by the implementation. This type is a Callable, and it is convertible to an instance of std::function
(or boost::function
).
Internally, function
(may) use type erasure to handle various complex, stateful "callable objects". This entails a dynamic allocation and a virtual dispatch in some (though not necessarily all) cases. Both bind
and function
are stateful, since they store the bound arguments.
The upshot is that you should avoid converting a bind expression to a function
object if possible. The bind expression itself may be cheaper, and you should not be afraid of using bind
(for example when binding member function pointers to instances and arguments). Use bind
freely, but conversion to function
only if you truly need to manage a heterogeneous collection of callable entities.
Here are two typical examples:
Bad; avoid this:
std::function<int(bool, char)> f = std::bind(&Foo::bar, x, 12);
void do_something(std::function<int()> func, int & acc)
{
acc += func();
}
Better; prefer this:
auto f = std::bind(&Foo::bar, x, 12); // unknowable type, but perfectly fine
template <typename F>
void do_something(F && func, int & acc) // can deduce unknowable types
{
acc += func();
}