Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers: is the simple canonical use bad from a performance point of view? If so what are the c++11-ish alternatives?

Tags:

c++

c++11

I'm using function pointers a lot in my c++ code, always in a way conforming to this simple canonical example (e.g. the functions have the same I/O, but the desired operation is only known at run time):

#include <iostream>
using namespace std;
 
int add(int first, int second){
    return first + second;
}
int subtract(int first, int second){
    return first - second;
}
int operation(int first, int second, int (*functocall)(int, int)){
    return (*functocall)(first, second);
}
int main(){
    int  a, b;
    int  (*plus)(int, int) = add;
    int (*minus)(int, int) = subtract;
 
    a = operation(7, 5, plus);
    b = operation(20, a, minus);
    cout << "a = " << a << " and b = " << b << endl;
    return 0;
}

I started using this a while ago simply because I found it simpler to use. As I learn c++ better, I find myself wondering: is this construct, in this context, bad from a performance point of view? If so why and what is the better c++11-ish alternatives?

I couldn't find precise guidelines for this simple usage case, from a performance point of view (though plenty of guidelines for more complicated cases)

EDIT:

Im implicitly assuming run of the mill x86 hardware.

like image 569
user189035 Avatar asked Dec 19 '22 11:12

user189035


1 Answers

If you are really worried about performance, you should consider doing compile-time dispatch - templatize operation; This will certainly work for your simple example; not sure if your real use needs true run-time operation binding (in which case this solution doesn't work).

    template <typename Functor>
    int operation(int first, int second, Functor f)
    {
        return f(first, second);
    }

    ...

    a = operation(7, 5, std::plus<int> /* since C++14, roll your own otherwise */);
    b = operation(20, a, std::minus<int>);

The performance overhead of calling through function pointers is certainly not negligible, especially for functions as short as add() and subtract(); That's the reason why the C++ std::sort beats the pants off of C's qsort routine for simple basic types.

like image 104
Stefan Atev Avatar answered May 18 '23 16:05

Stefan Atev