2015-02-28 - minimizing template code bloat

probably the most common technique is to use template-based interface to a non-template implementation. thanks to this we have generic API and no code bloat underneath.

for example to get a compile-time known C-string array size and process we can use this trick:

template<unsigned N>
void process(const char (&str)[N])
{
  // ...lots of string processing here...
}

but then, for each and every array size we'll have a duplicated code inside the binary. instead we can do this, to eliminate bloat but maintain flexibility:

void processImpl(char const* str, unsigned arraySize)
{
  // ...lots of string processing here...
}
 
template<unsigned N>
void process(cosnt char (&str)[N])
{
  processImpl(str, N);
}

this trick can also be applied by STL vendors to minimize code bloat for container's holding pointers. when this is applied we do not have gull-blown symbols for std::vector<int*> and std::vector<char*>, but just std::vector<void*> (or similar) that is wrapped around in proper casts to ensure type safety. this all can be inlined then and binary gets smaller for free. this trick is called thin template.

recently i've learned about one more interesting trick: SCARY iterators (paper with full description and measurements). the idea is to keep all iterators of the same concept (ex. random access iterators) the be of the same type. it can further minimize code bloat on code where iterators are used. this usually mean algorithms. idea is not new, but probably worth trying (AFAIC MSVC implements it already). it has also been proposed to become a part of the standard.

blog/2015/02/28/minimizing_template_code_bloat.txt · Last modified: 2021/06/15 20:09 by 127.0.0.1
Back to top
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0