3 ms·
In plain C we can make virtual function calls faster by forwarding the pointers into the object instance. Say we have this: int obj_api(object *o, char *ar
by kazinator 4y ago
In plain C we can make virtual function calls faster by forwarding the pointers into the object instance.
Say we have this:
int obj_api(object *o, char *arg)
{
return o->ops->api(o, arg);
}
that's representative of how C++ virtual functions are commonly implemented. It gets more hairy under multiple inheritance and such.
It requires several dependent pointer loads. We must access the object to retrieve its ops pointer (the vtable) and then access the vtable to get the pointer to the function, and finally branch there.
To call that function a little faster we can go to this:
int obj_api(object *o, char *arg)
{
return o->api(o, arg);
}
in other words, forward the api function pointer from the static table to the object instance. Ok, so now each time we construct a new object, we must initialize o->api. And the pointer takes up space in each instance. So there is a cost to it. But it blows away one dependent load. And the "clean" structure of the program has not changed; it has the same design with virtual functions and all.
We could do this for some select functions that could benefit from being dispatched a little faster.
I don't think there is a way in C++ to tell the compiler that we'd like a certain virtual function to be implemented faster, at the cost of taking up more space in the object instance and/or more time at object construction time.