Angs
Angs

Reputation: 1655

Difference between __always_inline and inline

There is a nice explanation of using inline instruction on another question

Could anyone explain me if there is any difference using inline and __always_inline on a header file?

And, when I would prefer __always_inline over inline or vice-versa?

Upvotes: 14

Views: 12265

Answers (3)

Dwight Guth
Dwight Guth

Reputation: 808

None of the answers here really answer the question of when you should use inline instead of always-inline, but the answer is fairly simple. You should pretty much always use inline unless you know exactly what you are doing and understand the performance implications of inlining the function you are annotating, because a bad inlining decision can in the worst case make a program much slower, and that includes both inlining when you shouldn't inline, and not inlining when you should inline. Generally speaking the compiler is quite intelligent at deciding this in the majority of cases, but it's not perfect; if it were, there would be no need for the inline keyword. It's true that the C language is quite esoteric about what precisely the inline keyword means, so you should read up before you use it, but it's better to leave ultimate say on whether to inline a function to the compiler as much as possible.

That being said, when you are optimizing critical parts of the code (and if you don't care about performance, why are you inlining things?), sometimes the compiler will make the wrong decision. In this case, you can correct the behavior with noinline or alwaysinline. But you should always familiarize yourself with the assembly of the functions in question before making this decision; too much inlining can increase code size and register pressure, and decrease cache locality. Too little can make code orders of magnitude slower.

Upvotes: 6

Jian Wang
Jian Wang

Reputation: 75

This article gives some useful information: https://www.kernel.org/doc/local/inline.html

"In Linux, the keyword "__always_inline" forces a function to be inlined, and "noinline" prevents a function from being inlined. We don't use the "inline" keyword because it's broken."

Upvotes: 1

sbh
sbh

Reputation: 447

Always inline function attribute indicates that a function must be inlined. The compiler attempts to inline the function, regardless of the characteristics of the function.

However with inline attributes the compiler does not inline a function if doing so causes problems. For example, a recursive function is inlined into itself only once.

__forceinline is equivalent to __always_inline.

Upvotes: 3

Related Questions