Why are templates compiling so slowly?

Large template projects are slowly compiling, and STL is the main culprit for this, apparently from empirical data. But why does it compile slowly?

I have optimized assemblies before by observing the inclusion of a header and combining compilation units, but I don’t understand why the template libraries are rather slow to compile.

+6
c ++ compilation templates code-generation
source share
4 answers

Template code should be taken as another language for generating C ++ code.

In this way of thinking, the template code must be analyzed, executed, then the compiler can generate C ++ code, which must be added to the current block file, and then we can compile all the code in C ++.

I have heard that not all compilers do this for sure, but this is the basic idea, and suppose that much more happens before actually compiling the code, since some code must be generated first.

+4
source share

C ++ is generally slowly compiled due to the ancient inclusion mechanism, which causes the compiler to recursively iterate over each header with all its declarations and definitions and everything that is included for each translation unit.

Templates are simply based on this β€œfeature”. But they require that all code also be in the headers, causing the compiler to also re-analyze all implementations of all included templates.

+12
source share

Part of the answer in your question. You cannot watch how the header includes templates, because the full implementation must be included in every compilation unit that uses them.

+1
source share

Think about what a real template is - this is not a real thing, but instructions on how to create real things.

In the case of C ++ templates, the header file does not contain the actual one, for example. 'vector', but instructions on how to build vector . Each time we create the source file, which is #include <vector> , the compiler should build a new vector code, perhaps several times, if we create a vector with different template parameters.

The construction of each source file is independent and does not know if you have already built a vector for another source file, so it creates a new one each time.

+1
source share

All Articles