Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a function is only called from one place, is it always better to inline it? [duplicate]

If a function is only used in one place and some profiling shows that it's not being inlined, will there always be a performance advantage in forcing the compiler to inline it?

Obviously "profile and see" (and in the case of the function in question, it did prove to be a small perf boost). I'm mostly asking out of curiosity -- are there any performance disadvantages to this with a reasonably smart compiler?

like image 441
Robert Fraser Avatar asked Dec 09 '22 04:12

Robert Fraser


1 Answers

No, there are notable exceptions. Take this code for example:

void do_something_often(void) {
    x++;
    if (x == 100000000) {
        do_a_lot_of_work();
    }
}

Let's say do_something_often() is called very often and from many places. do_a_lot_of_work() is called very rarely (one out of every one hundred million calls). Inlining do_a_lot_of_work() into do_something_often() doesn't gain you anything. Since do_something_often() does almost nothing, it would be much better if it got inlined into the functions that call it, and in the rare case that they need to call do_a_lot_of_work(), they call it out of line. In that way, they are saving a function call almost every time, and saving code bloat at every call site.

like image 65
Variable Length Coder Avatar answered Feb 16 '23 04:02

Variable Length Coder