views:

467

answers:

3

I'm in the process of implementing a platform independent wrapper for dynamically loaded libraries. Of course when I load functions from the libraries I need to store them as pointers for future use. I thought of using boost::function's for that instead of normal function pointers. Sure, that will increase compile time, but that's not what I am afraid of. Rather:

What is the overhead introduced by boost::function when calling the stored function? Is there one? How big is it?

I guess I won't have much overhead when calling such functions from time to time, however, how about functions that get called a lot? (extreme example, glVertex on a loaded GL library). How much would it hurt performance?

Source-diving boost didn't answer much :>.

Also if it's compiler dependant, I'm mainly interested in GCC and MSVC.

+3  A: 

As stated in the Boost documentation, invoking a boost::function incurs the cost of one call through a function pointer in most cases. In other words, if you were going to have to use function pointers anyhow, it's a wash, and you get a bunch of enhanced functionality for free.

Nick Bastin
+1  A: 

boost::function made it into tr1, so it's std::tr1::function on modern compilers, and just std::function on really modern compilers.

In any case, as you've observed, std::function has non-zero overhead for creation (including creating copies of the object). In theory, it should have the same overhead as a raw function pointer for invocation; ie there is one level of indirection - but really smart compilers can inline that level of indirection.

There is, of course, things you can store in a std::function that can't be fit or stored in a function pointer.

Terry Mahaffey
+2  A: 

Take a look here for a discussion and comparison of various function wrapper implementations.

Nikolai N Fetissov
This is a very interesting comparison indeed!
Kornel Kisielewicz