Search code examples
c++performanceboostc++11boost-bind

C ++ Boost Bind Performance


Are there any performance impacts (positive or negative) when binding functions (using Boost Bind) ?


Solution

  • Maybe, may not be. It depends.

    The result of std::bind (or also boost::bind) is a so-called "bind expression", which has an un­know­able type determined by the implementation. This type is a Callable, and it is convertible to an in­stance of std::function (or boost::function).

    Internally, function (may) use type erasure to handle various complex, stateful "call­able objects". This entails a dynamic allocation and a virtual dispatch in some (though not neces­sari­ly 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 bind­ing 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();
    }