Will there be a performance hit on including unused header files in C/C++?

两盒软妹~` 提交于 2019-12-01 16:31:11
Eugene Podskal

COMPILATION:

If something is included then it has to analyzed even if it will never be actually compiled and linked, so compilation time will increase for sure - Do not include unused headers.

RUNTIME:

It has been already mentioned by @DonReba that unused headers may include some pragma directives that can change the resulting executable, but usually it won't be the case.

Most of the unused functions and declaraions will be optimized out, excluding some specific cases - Do unused functions get optimized out?. The resulting exe may become a bit bigger, but those functions and variables won't be used, so overall impact will be minimal. - - Nonetheless, do not include unused headers.

SUMMARY:

If you can modify your source code to not include anything unneeded - modify it.

Personnaly I prefer to have self-contained modules(headers), that include everything they need - nothing more, nothing less. Such modules can be added and removed without hindsight and possibility that some unneeded dependency has been left. They are still not panacea, but coupled with attentiveness and some code analysis they will keep your program free from deadweight headers.

EDIT:

Precompiled headers:

Precompiled headers are used to reduce compilation time for often used, but rarely changed headers(system headers, huge project headers), so if those unused headers are included in the precompiled header, then the compilation time effect during subsequent compilations will be minimized. Still, all runtime issues, no matter how small they are, stay the same as for simple header includes.

Short answer to the question asked: No.

Long answer:

More headers mean marginally more chance of some problem appearing that might manifest as a performance issue, but it's really not a concern.

Many consider it poor style to do as you plan, but there are also those that consider it acceptable.

One of the key reasons for avoiding this style is that it will make it easier to get circular dependencies.

I would discourage it due to the compile time issue where I do not have pre-compiled headers.

Depends on compiler. Today's most compilers are smart and use precompiled headers to improve performance. I use GCC compiler which supports precompiled header and AFAIK does not affect performance.

It is possible that inclusion of an extra header would produce different runtime code due to overriding a preprocessor directive. But this would not be a normal situation.

Visual C++, GCC, and Clang support precompiled headers for improving compilation times for use cases like yours.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!