Benefits of declaring a function as “inline”?

前端 未结 10 1865
天涯浪人
天涯浪人 2020-12-09 14:01

Every time I read about the \"inline\" declaration in C it is mentioned that it is only a hint to the compiler (i.e. it does not have to obey it). Is there any benefit to ad

相关标签:
10条回答
  • 2020-12-09 14:34

    The declaration is pretty much useless and quite different from the original intent. Compilers have taken much more liberty wrt what and what not to inline (IMO).

    It's a hint to the compiler, using it will help you and have the intended significance only sometimes.

    If you need to write performance critical programs, do not rely on the compiler (knowledge of performance & optimization is not learned in a day). There's usually a way to override the compiler's judgement (not just hint at your preference), to force inlining. This is the way I declare a function/method inline, more than 95% of the time (knowing also when it is implicit). If/When you know you'd need to know how to inline properly, then employ force-inlining as well, but do learn when and how to use it.

    Inlining is not a silver bullet to better performance; it can have negative effects. Abuse of inlining can have some scary consequences in extreme cases, but usually performance is a little worse and binaries are larger when used improperly. Proper use of inlining can have considerably positive results.

    Inlining is also helpful to remove symbols which would otherwise be exported, reducing the binary, depending on the number of instances and size.

    Another thing: You'll get different linkage with C++.

    0 讨论(0)
  • 2020-12-09 14:35

    There are two reasons to use the inline keyword. One is an optimization hint, and you can safely ignore it; your compiler is like to ignore it too. The other reason is to allow a function to exist in multiple translation units, and that usage is strictly necessary. If you put a function into a .h header file for example, you'd better declare it inline.

    0 讨论(0)
  • 2020-12-09 14:40

    You can't be absolutely sure the compiler will catch the "critical" sections of your code: use "inline" when you know it matters.

    A compiler isn't a profiler.

    0 讨论(0)
  • 2020-12-09 14:41

    Since it's only a hint to the compiler, the compiler is free to ignore it, and likely will. The compiler has a lot of relevant information you don't have, such as how much of a cache line a loop will take up, and can inline or not on a case-by-case basis.

    It's just a hint, so using it is unlikely to hurt anything. You almost certainly should avoid any compiler-specific things that force functions to be inlined or not inlined.

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