Why is inlining considered faster than a function call?

前端 未结 16 1508
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 04:04

Now, I know it\'s because there\'s not the overhead of calling a function, but is the overhead of calling a function really that heavy (and worth the bloat of having it inli

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 04:23

    (and worth the bloat of having it inlined)

    It is not always the case that in-lining results in larger code. For example a simple data access function such as:

    int getData()
    {
       return data ;
    }
    

    will result in significantly more instruction cycles as a function call than as an in-line, and such functions are best suited to in-lining.

    If the function body contains a significant amount of code the function call overhead will indeed be insignificant, and if it is called from a number of locations, it may indeed result in code bloat - although your compiler is as likely to simply ignore the inline directive in such cases.

    You should also consider the frequency of calling; even for a large-ish code body, if the function is called frequently from one location, the saving may in some cases be worthwhile. It comes down to the ratio of call-overhead to code body size, and the frequency of use.

    Of course you could just leave it up to your compiler to decide. I only ever explicitly in-line functions that comprise of a single statement not involving a further function call, and that is more for speed of development of class methods than for performance.

提交回复
热议问题