Can a modern C / C ++ compiler better optimize the code in the header?

I often heard that it is wrong to put code in the header, but it was customary to put short functions in the headers, in part to improve compiler optimization.

Inline keywords can help the compiler determine which functions should be inlined, but beyond that, is there any other reason to have short critical performance functions in the headers? Or does it not matter to modern compilers?

+5
source share
1 answer

Technically, the inline only means that the definition is allowed in multiple translation units. That is, if you have a built-in function defined in the header file, and this header is included in several source files, then this is normal. For a non-inline function without a template, this would be illegal.

But compilers can and can take the opportunity to see the code of the called function. This happens not only for built-in functions, but also for any other functions whose code may be visible. Many compilers try to make a good guess about whether to embed code. Having built-in code can make a program larger or smaller, faster or slower. If the compiler can determine that the code is likely to be faster and smaller when the code is embedded, then it will do so. Otherwise, he must take into account the compromise.

Many modern compilers can optimize connection times when code that was not embedded at the beginning can be embedded during the link phase with some cost in connection time. There may be certain optimization possibilities that are lost when there is a delay before the connection.

In my own experience, I found that creating small functions is built-in, as a rule, it is always a victory for both size and speed. For larger functions, I often see programs doing faster, but more, but I also saw that they rarely make programs slower and bigger. If the performance of a particular function is important, you will need to take measurements to help make the choice in the row or not.

+4
source

Source: https://habr.com/ru/post/1211425/


All Articles