msvc's man page says:
__declspec(noinline)
tells the compiler to never inline a particular member function (function in a class).It may be worthwhile to not inline a function if it is small and not critical to the performance of your code. That is, if the function is small and not likely to be called often, such as a function that handles an error condition.
Keep in mind that if a function is marked noinline, the calling function will be smaller and thus, itself a candidate for compiler inlining.
class X { __declspec(noinline) int f() { return 0; } // will not inline };
However, I still cannot understand:
What are the differences, or benefits, between
class X {
__declspec(noinline) int f() {
return 0;
} // will not inline
};
and
class X {
int f() {
return 0;
}
};
?
Under normal circumstances, there is no benefit. The compiler has the option of inlining or not inlining a function on a per-call basis, assuming it knows the definition of the function at the call site (either because the function definition is in the same translation unit, or because you've enabled global link-time optimization).
Benefits come down to one of three things: When you want to optimize your code and you think you know better than the compiler, when you explicitly want to keep the function's code from being put in a particular object file, or when you're trying to debug stuff.
In the first case, it is occasionally useful to prohibit inlining to reduce code size, generally to reduce pressure on the instruction cache. This is rarely the case, and should never be done except based on the evidence from a profiler. If you don't know about icache misses then this is not relevant to you, and enabling global link-time optimization and profile-guided optimization are far easier and more effective approaches to getting inlining "right".
In the second case, you may occasionally want to make one object file the sole object file that needs to be recompiled when a function is changed. Getting this right without inadvertently violating the One Definition Rule is tricky and relies on details of how the objects are linked together. It is again not something that's relevant unless you understand the low-level details.
In the final case, marking a function as noinline
can make it easier to step through code in the debugger, particularly optimized code, by preventing the compiler from mixing code for multiple functions and by clearly demarking function parameters and return values. It's also useful in cases where you suspect bugs in the compiler itself, since it allows you to localize them to a particular function. This is the most likely reason you'll have for using noinline
, if you ever do.