Benefits of inline functions in C++?

后端 未结 14 1403
终归单人心
终归单人心 2020-11-22 05:30

What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today\'s opt

相关标签:
14条回答
  • 2020-11-22 06:05

    Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.

    Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.

    Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.

    I could see a situation like this making a detectable difference:

    inline int aplusb_pow2(int a, int b) {
      return (a + b)*(a + b) ;
    }
    
    for(int a = 0; a < 900000; ++a)
        for(int b = 0; b < 900000; ++b)
            aplusb_pow2(a, b);
    
    0 讨论(0)
  • 2020-11-22 06:08

    I'd like to add that inline functions are crucial when you are building shared library. Without marking function inline, it will be exported into the library in the binary form. It will be also present in the symbols table, if exported. On the other side, inlined functions are not exported, neither to the library binaries nor to the symbols table.

    It may be critical when library is intended to be loaded at runtime. It may also hit binary-compatible-aware libraries. In such cases don't use inline.

    0 讨论(0)
提交回复
热议问题