Search code examples
c++inlineinline-functions

What are the benefits of inline functions?


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 optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?


Solution

  • 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);