Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a function that only calls another function slow things down?

I saw some code that was something like this

int *func2(int *var) {
    //Do some actual work
    return var;
}

int *func1(int *var) {
    return func2(var);
}

int main() {
    int var;
    var = func1(&var);
    return 0;
}

This seems like an incredible waste to me but I figured the intermediate function might have previously had two function that it could call or there are some plans for expansion in the future. I was just wondering if compilers like gcc can detect this sort of thing and eliminate the useless function in the actual program or if this sort of thing actually wastes CPU cycles at runtime?

like image 788
chinakow Avatar asked Dec 04 '22 05:12

chinakow


1 Answers

Don't do premature optimization. Focus on writing readable code. Even without optimization, the extra function call probably has a minimal effect on performance. The compiler may choose to inline it.

If you have performance issues later, you can test and profile to find the bottlenecks.

like image 167
Matthew Flaschen Avatar answered Jan 19 '23 00:01

Matthew Flaschen