Search code examples
c++performancevirtual-functionsboost-function

C++ virtual function call versus boost::function call speedwise


I wanted to know how fast is a single-inheritance virtual function call when compared to one same boost::function call. Are they almost the same in performance or is boost::function slower?

I'm aware that performance may vary from case to case, but, as a general rule, which is faster, and to a how large degree is that so?

Thanks, Guilherme

-- edit

KennyTM's test was sufficiently convincing for me. boost::function doesn't seem to be that much slower than a vcall for my own purposes. Thanks.


Solution

  • As a very special case, consider calling an empty function 109 times.


    Code A:

    struct X {
                virtual ~X() {}
            virtual void do_x() {};
    };
    struct Y : public X {}; // for the paranoid.
    
    int main () {
            Y* x = new Y;
            for (int i = 100000000; i >= 0; -- i)
                    x->do_x();
            delete x;
            return 0;
    }
    

    Code B: (with boost 1.41):

    #include <boost/function.hpp>
    
    struct X {
        void do_x() {};
    };
    
    int main () {
        X* x = new X;
        boost::function<void (X*)> f;
        f = &X::do_x;
        for (int i = 100000000; i >= 0; -- i)
            f(x);
        delete x;
        return 0;
    }
    

    Compile with g++ -O3, then time with time,

    • Code A takes 0.30 seconds.
    • Code B takes 0.54 seconds.

    Inspecting the assembly code, it seems that the slowness may be due to exceptions and handling the possibility and that f can be NULL. But given the price of one boost::function call is only 2.4 nanoseconds (on my 2 GHz machine), the actual code in your do_x() could shadow this pretty much. I would say, it's not a reason to avoid boost::function.