5

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.

Gui Prá
  • 5,559
  • 4
  • 34
  • 59

1 Answers1

7

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.

CashCow
  • 30,981
  • 5
  • 61
  • 92
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 1
    And where is the single-inheritance in case A? ;) – Georg Fritzsche Jan 30 '10 at 08:59
  • 1
    @gf: You know how vtable works? Inheritance doesn't matter because the whole vtable is copied. – kennytm Jan 30 '10 at 09:02
  • 3
    While such a quick test is indeed very helpful, it only tells you how the code behave performance-wise under you specific conditions (test case, compiler, compiler settings, platform etc.). This is not to deny your result, I'm just reminding to be careful when generalizing from a single test case. – sbi Jan 30 '10 at 09:18
  • Roughly yes, but not what every implementation actually does. – Georg Fritzsche Jan 30 '10 at 12:41