This is an important doubt I have. Are a template function slower that literal functions (that is with full type declaration)?
-
4This is an example of a question that is *not constructive*. You seem to have made no effort of finding an answer on your own. – Björn Pollex Nov 15 '11 at 08:01
-
Take a look at http://stackoverflow.com/questions/2442358/do-c-templates-make-programs-slow – Jan S Nov 15 '11 at 08:04
-
3@Björn "not constructive" does not mean that at all. – David Heffernan Nov 15 '11 at 08:04
-
2@DavidHeffernan: Your comment actually made me read the descriptions for the close reasons again, and you are right, I was mistaken here (must have misread that before). It seems that the appropriate action would have been to downvote (*This question does not show any research effort*). – Björn Pollex Nov 15 '11 at 08:11
-
@tonnot Please note that you have never accepted an answer here, and never voted. Members of this community are encouraged to do both: see the [faq]. – David Heffernan Nov 15 '11 at 09:14
6 Answers
Based on my testing (e.g., in a previous answer), a template function can be the same speed as a non-template function, but often won't be. The big difference is that a template function will often receive its parameters by reference, just in case they're "big". A non-template function is much more likely to receive its arguments by value, which will often improve speed if the parameter(s) is/are reasonably small. If both receive their arguments by reference, however, I've found that in at least some cases, the template will actually be a bit faster than the non-template code.
Also note, however, that a functor will frequently beat both (e.g., exactly happened in the testing cited above).

- 1
- 1

- 476,176
- 80
- 629
- 1,111
In genral there will be no difference because the compiler expands the instantiated template into the same code as if you wrote it out yourself without templates.
In other words the templates are processed at compile time and not runtime.

- 601,492
- 42
- 1,072
- 1,490
No, they are compiled into regular functions at compile time.
At runtime they work exactly the same as any other function.

- 48,127
- 24
- 147
- 185
I think the correct answer is as follows: template functions have the same runtime performance, but could possibly take longer time to compile in some circumstances.

- 32,368
- 48
- 194
- 335
Every template will receive a type, and so be a "literal function" after compiling. So I guess they are not slower..

- 9,289
- 3
- 30
- 45
No. When a template is instantiated the compiler generates a function using the template parameters produces a function that is exactly as though you had written a non-template function using those types.

- 86,085
- 15
- 179
- 244