Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANSI C: If a function pointer points to executable code does that mean less execution overhead than simply invoking the function? [duplicate]

We know that using function pointers in C can be quite helpful when used in the proper scenarios (calling a function at runtime vs compile time, making the code more readable, etc.), but there isn't much literature around simple function invocation vs using a function pointer.

void foo(void) {
    printf("hello\n");
}

int testFcn(void) {

    // simple invokation
    foo();

    return 0;
}

// Or, declare function pointer and assign
void (*myFunc)(void) = foo;

int testFcn(myFunc) {

    // Function pointer invokation.
    myFunc();

    return 0;
}

Perhaps the only real way to tell is to analyze the .lst files and .map files?

like image 720
S_Balb Avatar asked Dec 31 '25 10:12

S_Balb


1 Answers

In general case, when function pointer is stored in data segment's memory, invoking a function through such a pointer will involve more overhead, not less overhead.

The real-life performance might vary greatly, depending on whether the pointer is in the CPU cache, already loaded into CPU register, properly predicted by branch prediction mechanism and other factors.

like image 80
AnT Avatar answered Jan 03 '26 05:01

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!