Reputation: 13575
I have two choices in my design. One is to just use one class with argument like
A::A(int i)
the other is to use template like
A<i>
I have many objects A<1>(), A<2>() and so on. I'm wondering if the second way affects the execution and compilation performance significantly.
Upvotes: 1
Views: 111
Reputation: 4387
You should never do exotic things (I consider non-type template parameters somewhat exotic) for performance unless you need to. You can always go back to refactor later if you need improved speed, size, compile time, etc. That being said, what is the difference?
By declaring a bunch of template classes, you are basically copy pasting the class definition over and over with that argument. This has a few effects:
Compile and Link Times:
Not only are you declaring N classes, templates also can't separate their body into a translation unit. This means that in every translation unit they are used, they are instantiated. This can drastically slow compile and link times.
Code Size and Fragmentation:
Because each class is independent, they will each have their own functions. This generally leads to an increase in code size, since even though the code can be very similar, they are independent types with their own member functions. Increased code size also has a negative performance impact due to caching, since more code has to be loaded to keep the program churning.
Restrictions:
Because the classes will be their own types, the templated classes will not "know" each other. They cannot be stored in the same array, vector, list, map, etc. You can do some polymorphism magic to store pointers to a shared base, but a bunch of pointers will generally perform far worse than a localized array or vector. You also can't do any run-time construction of A
based on the input. This may or may not be applicable, but think about the future too. Will you absolutely never need to construct based on some runtime variable? Will you absolutely never need to hold an array of A
somewhere?
Compile Time Knowledge of Argument:
Now here's the one major benefit. You know i
at compile time. This means you can do a couple of pretty nifty things. With C++11, you could write constexpr equations (or in C++14, prettier constexpr equations.) You could do metatemplate programming to create some other stuff at compile time. This leads to some unique cases that can reduce execution time at a major complexity and compile/link time cost. But in some scenarios it is necessary. I would never go with a solution involving this though, unless profiling told me too.
Upvotes: 3