Search code examples
c++visual-studioinline-functions

When should I use __forceinline instead of inline?


Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states:

The __forceinline keyword overrides the cost/benefit analysis and relies on the judgment of the programmer instead.

This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am I supposed to know that it's wrong?

In what scenario is it assumed that I know better than my compiler on this issue?


Solution

  • The compiler is making its decisions based on static code analysis, whereas if you profile as don says, you are carrying out a dynamic analysis that can be much farther reaching. The number of calls to a specific piece of code is often largely determined by the context in which it is used, e.g. the data. Profiling a typical set of use cases will do this. Personally, I gather this information by enabling profiling on my automated regression tests. In addition to forcing inlines, I have unrolled loops and carried out other manual optimizations on the basis of such data, to good effect. It is also imperative to profile again afterwards, as sometimes your best efforts can actually lead to decreased performance. Again, automation makes this a lot less painful.

    More often than not though, in my experience, tweaking alogorithms gives much better results than straight code optimization.