Benefits of inline functions in C++?

后端 未结 14 1394
终归单人心
终归单人心 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);
    

提交回复
热议问题