Why is boost::function slow?

boost, c++, performance

Solution

Regular functions can be inlined by the compiler if possible, but `boost::function` can never be inlined. That is one big difference.

The second difference is, `boost::function` implements type-erasure which means it uses indirection to invoke the actual function. Means it first calls a virtual function which then invokes your function. So typically it involves (minimum) two function calls (one of them is `virtual`). That is huge difference.

So based on this analysis, one could infer this (without even writing test code):

slowest ------------------------------------------------------> fastest 
        boost::function < virtual function < regular function 
slowest ------------------------------------------------------> fastest

which is indeed the case, in your test code.

Note that it is true for `std::function` also (which is available since C++11).

Problem

I was doing some timing tests and one of my tests was to compare different ways of calling functions. I called N functions using various means. I tried regular function calls, virtual function calls, function pointers, and boost::function. I did this in Linux using gcc and -O3 optimization. As expected virtual calls are slower than regular function calls. However the surprising thing is that boost::function clocked in at 33% slower than the virtual calls. Has anyone else noticed this? Any clue to why this is?

Original source