Skip to main content
GameDev.net gamedev.net
🔒 Locked

Why template?

Started by psae0001 Nov 1, 2005 at 1:39 AM 9 replies 1.1k views
Original Post
psae0001
psae0001
Hello, Almost every tutorials I read, and every post I encounted, perfer STL or template. I'm not really C++ type of person, but C. I know smart pointers such kinda thing save alot of headache. But how about perfromence? Does it really matter for today's hardware or ? I'm just curious. Thanks.
Grain
Grain
Templates are evaluated at compile time so I don’t think it has any performance impact. But I'm not 100% certain, someone more knowledgeable than me can confirm?
Cocalus
Cocalus
Performance wise templates are normally faster or the same speed (you must compile with optimizations on for it to be faster), since you can inline with templates.

For an example write up a test case to compare std::sort and qsort. (Make sure optimizations are on for the test and that you aren't making a debug version)

[Edited by - Cocalus on November 1, 2005 2:50:08 AM]
_goat
_goat
Templates aren't actually a run-time thing, they're resolved at compile-time, and consequently won't generate any overhead themselves. Smart pointers will incur a slight performance decrease, but their benefits outweigh their negatives significantly. There is always the option of changing them to nothing more than a pointer wrapper (which would most likely be compiled away by a smart compiler) for release mode if you're really concerned. With today's hardware, and 3,600,000,000 instructions a second, smart pointers will more than likely not be the bottleneck in your program.
iMalc
iMalc
If you have a templated class and you instantiate it for a number of different types, then it will generate the necessary code for each type.

In C you would simply have, for example, a list class that simply stored items in a void pointer and did lots of yucky type-casting. However it did make the compiled code smaller.
For embedded devices it can matter, and at my work we have done exactly the above with our list class because code space is more limited. However in programming for a PC you don't really have to worry about such things. Just use whatever is most suitable.
CTar
CTar
As some said you shouldn't worry about performance regarding templates, if you have this code:

template<typename T>void Foo(const T& A){    return T(A);}int main(){    Foo<int>(6);    Foo<float>(6.0F);    return 0;}


This would be the same as doing:

void FooInt(const int& A){    return int(A);}void FooFloat(const float& A){    return float(A);}int main(){    FooInt(6);    FooFloat(6.0F);    return 0;}


I expect the code to be generated to be 100 % equal (it might be equal to a single return 0 statement since the other functions will be optimized out). You should worry about 3 things when working with templates:
1) Program size (probably not important) - if you have a single templated class which you pass 20 different types in the template argument list 20 different classes will be generated.
2) Compile time - Templated code can take quite a while to compile
3) Support - Some compilers (VC6 for example) doesn't support templates very well in 100 % standard C++ code might not compile.
Emmanuel Deloget
Emmanuel Deloget
Quote:
Original post by psae0001
Hello,

Almost every tutorials I read, and every post I encounted, perfer STL or template. I'm not really C++ type of person, but C. I know smart pointers such kinda thing save alot of headache. But how about perfromence? Does it really matter for today's hardware or ? I'm just curious.

Thanks.


The main thign about template is not efficiency or performance, but writing generic type-safe code which is far more important from a professional coder point of view. This is why people on Gamedev advocates the use of the STL: it is very generic, and works very well - some STL implementation may have bugs (for example, the nasty std::string+multiprocessor problem in VC6) but generally you can trust your compiler's implementation much more than any implementation you could make yourself.

Regards,
MaulingMonkey
MaulingMonkey
Quote:
Original post by psae0001
But how about perfromence?

As allready mentioned, templates are all dealt with at compile time, no run time preformance hit there.

As for smart pointers, this varies more.

Any modern compiler will inline many/most smart pointer function calls, since they're usually simple enough. If using a simple local scoped smart pointer such as std::auto_ptr, boost::scoped_ptr, or boost::scoped_array, it won't preform any slower than the manual equivilant - most likely, they'll inline into the exact same assembly.

When you get to more intelligent smart pointers, they can use more CPU cycles than the individual operations on the raw pointer, but that's doing bookkeeping that in theory you would otherwise need to do yourself. So you'd want to use boost::scoped_ptr, not boost::shared_ptr, for something that's only going to exist in that function. Your compiler may be smart enough to optimize shared_ptr down to the same assembly as scoped_ptr, but I wouldn't bet on that.

Basically, when appropriately used, smart pointers only do what you'd otherwise have to do yourself - meaning they're no slower. You can misues them, but you can misuse just about anything.

-Mike
haegarr
haegarr
What actually happens when templates come to play depends heavily on _how_ one uses them. In practise, runtime penalties are not to be expected, as already said in most posts above (but see the comment below the next paragraph).

However, code size may vary. You may have _less_ code in comparison to a non-template version because the compiler/linker is able to generate only those functions from templates that are actually needed. You may have _the same_ amount of code if you say that you program a library and hence explicitely wants all functions be available. You may also have _more_ code if you instantiate the template in different compile units that are later not able/allowed to be combined, so that the linker will not be able to remove duplicate code. It depends on (a) how you control template instantiation (keywords are implicit/explicit instantiations) and (b) how good your compiler/linker is.

(So one could also have an esoteric though like: If there is less/more code then less/more cache misses may occur, and hence templates may be faster/slower ;-)

IMHO, templates are worth the problems they make. Especially in mid to large scale projects they may avoid type errors and copy-&-paste mistakes, and may improve the programmers overview due to source code reduction.
stylin
stylin
One way that using templates can speed up your code during runtime is using static polymorphism as opposed to dynamic polymorphism. Compare these two methodologies, the first one uses dynamic polymorphism, the second employs static polymorphism (code is squished for brevity):

#include <iostream>// an interface for some useless objectclass interface {public:      virtual void foobar() const = 0;};// a few implementations of said interfaceclass implementation_a : public interface {public:      void foobar() const { std::cout << "implementation a\n"; };};class implementation_b : public interface {public:      void foobar() const { std::cout << "implementation b\n"; };};// function that uses common interface (note the virtual function call)void use_dynamic_polymorphism( interface * const pb ) { pb->foobar(); }// function template that uses implementations directly (no virtual function call)template< typename implementation >void use_static_polymorphism( implementation & impl ) { impl.foobar(); }int main() {   // here we use base pointers and virtual function calls for dynamic polymorphism, or   // polymorphism that occurs at run-time   interface * pinterface = new implementation_a;   use_dynamic_polymorphism( pinterface );   delete pinterface;   pinterface = new implementation_b;   use_dynamic_polymorphism( pinterface );   delete pinterface;   // here we use concrete objects and a function template for static polymorphism, or   // polymorphism that occurs at compile-time.   implementation_a i_a;   implementation_b i_b;   // this saves us a function call, new/delete pairs, and is type-safe   use_static_polymorphism( i_a );   use_static_polymorphism( i_b );   return 0;}
:stylin: "Make games, not war." "...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.