devxlogo

Do Templates Increase Executable Size ?

Do Templates Increase Executable Size ?

Question:
Since template code is generated at compile time, it implies that there should be a separate set of code for each template objects created. Does that mean templates increase the executable size?

Answer:
Not necessarily. Whether templates increase the program’s size depends on how you’re actually using them in your code and the compiler’s cleverness. It is true that injudicious usage of templates can cause a problem known as “code bloat”. For example, one of the following instances of the vector template is redundant; on a 32-bit platform, both of them result in two copies of identical code:

vector  vi; vector  vl;

Worse yet, because pointer types are distinct, excessive instantiation of pointer-based templates also creates redundant copies of identical code:

// Shape is base of Rectangle and Squarevector  vs; vector  vr;vector  vsq;

In this case, three distinct copies of vector are instantiated, one for each pointer type. You can easily avoid this redundancy by using polymorphism and a vector of a pointer to the base class, i.e., vector :

Rectangle rec;vs.pushback (&rec); // pointer to derived// calls Rectangle::Draw if vs[0] is of type Rectangle*vs[0]->Draw();

In fact, sophisticated use of templates can actually reduce the program’s size rather than increase it. This is because the compiler must generate code on a selective basis: it generates code only for member functions that are actually used in the program, whereas member functions that aren’t referenced in the program aren’t generated. Thus, if vector has 25 member functions (including constructors, assignment operator, and destructor). However, if a program only uses the push_back(), operator [], default constructor and destructor of vector . In this case, the compiler doesn’t generate code for the rest of the member functions. Consequently, program’s size is reduced. By contrast, if you’d chosen to implement vector as an ordinary class (i.e., not a class template), the compiler would have generated code for all the member functions of that class.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist