Hacker News new | ask | show | jobs
by hellofunk 3740 days ago
Well, much of C++ involves virtual function calls, and those are indeed slower than non-virtual calls. C doesn't have virtual calls, so that is perhaps one reason why C is generally assumed to be faster. That doesn't mean you must use virtual functions in C++; in fact, I don't use inheritance in my own code whatsoever, therefore I avoid the virtual calls but more importantly the restrictions that can creep into a tight OO hierarchy.

And std::function, from what I understand, is generally not as fast as a function pointer, a stored lambda, a function object, since it must do some run-time checks to see how to call what it is storing.

2 comments

However, every sufficiently complex C program re-invents vtables (or has an even worse generic dispatching system), so you're often no worse off . . .
The only virtual call that you necessarily get with polymorphism is the destructor call.

Whenever you need to make a function virtual in C++, you'd need to store a function pointer in an equivalent C design, somehow.

Are you suggesting that C++ virtual functions have the same overhead as a C function pointer? I've never heard that; with the virtual call, there is the lookup + the invocation; perhaps a C app that stores function pointers in a hash map also has this sort of lookup, is that what you mean?
Vtable lookup in a typical C++ implementation is just loading a fixed offset in an array. In C terms, it's basically doing object->vtable[42]. In C code with function pointers, you're typically performing that exact same operation. You can go slightly faster if you store the function pointer in the object directly, at the cost of increased memory consumption per object if you have more than one function pointer.