Why should I ever use inline code?

2019-01-08 05:28发布

I'm a C/C++ developer, and here are a couple of questions that always baffled me.

  • Is there a big difference between "regular" code and inline code?
  • Which is the main difference?
  • Is inline code simply a "form" of macros?
  • What kind of tradeoff must be done when choosing to inline your code?

Thanks

16条回答
成全新的幸福
2楼-- · 2019-01-08 05:51

First of all inline is a request to compiler to inline the function .so it is upto compiler to make it inline or not.

  1. When to use?When ever a function is of very few lines(for all accessors and mutator) but not for recursive functions
  2. Advantage?Time taken for invoking the function call is not involved
  3. Is compiler inline any function of its own?yes when ever a function is defined in header file inside a class
查看更多
神经病院院长
3楼-- · 2019-01-08 05:55

inlining is a technique to increase speed. But use a profiler to test this in your situation. I have found (MSVC) that inlining does not always deliver and certainly not in any spectacular way. Runtimes sometimes decreased by a few percent but in slightly different circumstances increased by a few percent.

If the code is running slowly, get out your profiler to find troublespots and work on those.

I have stopped adding inline functions to header files, it increases coupling but gives little in return.

查看更多
Rolldiameter
4楼-- · 2019-01-08 05:59

Inline differs from macros in that it's a hint to the compiler (compiler may decide not to inline the code!) and macros are source code text generation before the compilation and as such are "forced" to be inlined.

查看更多
Viruses.
5楼-- · 2019-01-08 05:59

The answer of should you inline comes down to speed. If you're in a tight loop calling a function, and it's not a super huge function, but one where a lot of the time is wasted in CALLING the function, then make that function inline and you'll get a lot of bang for your buck.

查看更多
登录 后发表回答