r/C_Programming • u/LemonLord7 • Oct 08 '26
Question Performance loss of mimicing interfaces with function pointers on modern compilers?
C does not have interfaces like languages such as C# or C++, but the cocnept can be mimicked by using function pointers. You might for instance have this:
// fruit_interface.h
typedef struct fruit_vtable
{
float (*get_weight)(void *object);
float (*get_density)(void *object);
const char *(*get_name)(void *object);
} fruit_vtable;
typedef struct fruit_interface
{
void *object;
const fruit_vtable *vtable;
} fruit_interface;
// banana.h
typedef struct banana
{
float weight;
float density;
} banana;
fruit_interface banana_as_fruit(banana *b);
--------------------------
// banana.c
static float banana_get_weight(void *object)
{
banana *b = (banana*)object;
return b->weight;
}
static float banana_get_density(void *object)
{
banana *b = (banana*)object;
return b->density;
}
static const char *banana_get_color(void *object)
{
(void)object;
return "yellow";
}
static const fruit_vtable banana_vtable =
{
.get_weight = banana_get_weight,
.get_density = banana_get_density,
.get_color = banana_get_color,
};
fruit_interface banana_as_fruit(banana *b)
{
return (fruit_interface) { .object = (void*)b, .vtable = &banana_vtable };
}
--------------------------
// main.c
static void print_fruit(fruit_interface fruit)
{
printf("weight: %.2f g\n", fruit.vtable->get_weight(fruit.object));
printf("density: %.2f g/cm^3\n", fruit.vtable->get_density(fruit.object));
printf("color: %s\n", fruit.vtable->get_color(fruit.object));
}
int main(void)
{
banana b = { .weight = 120.0f, .density = 0.95f };
fruit_interface fruit = banana_as_fruit(&b);
print_fruit(fruit);
return 0;
}How does something like this affect performance in terms of speed and cpu usage but also memory? I know modern C compilers can be really powerful and do a lot of optimizations and even more so with link time optimizations.
Of course it depends on the bigger project as a whole, and I understand that a if you have thousands of fruit_interface variables that all point to many different fruit_vtables and are used many times per second/cycle, then that will be very different from e.g. a hardware_interface that just loads some data once in an initialization function at program start.
The question here is pretty open (and the above is just to show clearly what I mean), and I am mostly looking for some general knowledge and guidance for when something like this is good and when it is bad, especially in the context of modern C code development with modern compilers and linkers.
I think it is really interesting to see how concepts in other languages, like C++, can be handled in C and what C is capable!
15
u/JimRayA Oct 08 '26
Calling functions in C is like calling standard methods on C++. Calling a function pointer on C is like calling a virtual method on C++. One extra memory reference is implicit in both, and there may be instruction pipeline effects. However, except for the most performance critical operations, function pointers are not significantly different from standard functions.
You can think of it this way. Both C and C++ do similar work for runtime selection of a function to be called, and they do similar work for compile time selection of functions to be called.
3
u/Rararror Oct 08 '26
You could do the same in assembler, the question is would you? as an exercise maybe
3
u/actguru Oct 08 '26
In general the performance cost of this style of polymorphism is tiny, but it depends on how often it is used. For example if you generalized a Pixel for processing graphics the cost might be very high. My issue with this type of vtable is that it is not very flexible, and I would advocate for a hash map of functions that is even slower but way more flexible.
4
u/tstanisl Oct 08 '26 edited Oct 08 '26
Have you considered container_of pattern? It saves you extra dereference of
objectand it is a lot more type safe and self documenting.EDIT.
The example adjusted to the techinique:
Note, that there is not a single cast in this code except one in
container_ofwhich has its own type checking. The code compiles without a warning in pedantic.One can even implement RTTI by comparing
vtablefields.One can put multiple "base" members into banana struct making multi-inheritance trivial. Take a look in source code of Linux kernel where this technique is used in countless places.
See godbolt.
3
u/Physical_Dare8553 Oct 08 '26
Do you mean in comparison to those other languages? Cuz this is almost exactly the same as what those languages do but you wrote it
1
u/QueefInMyKisser Oct 08 '26
You can consider alternative patterns like tagged unions (typically an enum followed by a union of structs) with manual dispatch (typically a switch statement).
This is more or less the same pattern as using variant and visit from the C++ standard library.
It can be faster as there’s better cache locality and branch prediction. One downside is it’s harder to maintain if you have a lot of types. Another is that the union will be the size of the biggest struct so it may waste memory if the types aren’t all similar in size.
Some C code implementing this uses X macros which can help keep the types and the switches in sync.
1
u/brigadierfrog Oct 08 '26
If you use either amalgamation build techniques like SQLite or LTO those function pointer tables are often removed from the call paths.
1
u/ScallionSmooth5925 Oct 08 '26
I would guess it's faster then something like C# because the vtable is a lot simpler
1
u/Classic-Rate-5104 Oct 08 '26
As far as I know, Linux kernel uses comparable techniques (C++ isn't allowed in the kernel). No one ever concluded the kernel is slow ...
0
u/tobdomo Oct 08 '26
It highly depends on the target architecture, the compiler and of course your application.
A functionpointer typically can't be optimized. The compiler has to fetch the function's address and do an indirect call. No inlining either, which may be the biggest optimization (think argument evaluation and object lifetime).
It is a good pattern for simplicity in many problems. E.g., when building a menu structure, object orientation is the way to go.