問題描述
我從很多人那里聽說使用模板會使代碼變慢.真的嗎.我目前正在建造一個圖書館.有些地方如果不創建模板,會導致代碼管理問題.到目前為止,我可以想到兩個解決此問題的方法:
I have heard from many people that usage of templates make the code slow. Is it really true. I'm currently building a library. There are places where if templates are not created, it would result in code management problem. As of now I can think two solutions to this problem:
使用#defines
use #defines
使用模板并在頭文件/庫本身中定義所有可能的類型,但不允許最終用戶創建模板實例.
Use templates and define all possible types in the header file/library itself but do not allow end user to make template instances.
例如typedef Graph
等
無論如何,是否可以限制用戶自己創建各種模板實例.
Is there anyway, to restrict user from creating various template instances on their own.
對上述查詢的幫助將受到高度重視.
Help on above queries would be highly regarded.
推薦答案
簡短的回答是否定的.如需更長的答案,請繼續閱讀.
正如其他人已經指出的那樣,模板沒有直接的運行時懲罰——即它們的所有技巧都發生在編譯時.然而,在某些情況下,它們可以間接地減慢速度.特別是,模板的每個實例化(通常)產生的代碼與其他實例化是分開和唯一的.在少數情況下,這可能會導致執行緩慢,因為它只是生成足夠多的目標代碼,使其不再適合緩存.
As others have already noted, templates don't have a direct run-time penalty -- i.e. all their tricks happen at compile time. Indirectly, however, they can slow things down under a few circumstances. In particular, each instantiation of a template (normally) produces code that's separate and unique from other instantiations. Under a few circumstances, this can lead to slow execution, by simply producing enough object code that it no longer fits in the cache well.
關于代碼大小:是的,大多數編譯器可以并且會為相同實例化的代碼折疊在一起——但是通常只有當實例化是真實的時才會出現這種情況完全相同的.編譯器不會不插入代碼來進行最微不足道的轉換,以獲得兩個細微不同的實例來相互匹配.例如,一個普通的函數調用可以并且將把 T *
轉換為 T const *
所以調用使用 const
或非 const
參數將使用相同的代碼(除非您選擇在 const
ness 上重載函數,在這種情況下,您可能已經專門為這兩種情況提供不同的行為).使用模板則不會發生這種情況——對 T *
和 T const *
的實例化將導致生成兩個完全獨立的代碼段.可能編譯器(或鏈接器)事后能夠合并兩者,但并不完全確定(例如,我肯定使用過沒有的編譯器).
With respect to code size: yes, most compilers can and will fold together the code for identical instantiations -- but that's normally the case only when the instantiations are truly identical. The compiler will not insert code to do even the most trivial conversions to get two minutely different instantiations to match each other. For example, a normal function call can and will convert T *
to T const *
so calls that use either const
or non-const
arguments will use the same code (unless you've chosen to overload the function on const
ness, in which case you've probably done so specifically to provide different behavior for the two cases). With a template, that won't happen -- instantiations over T *
and T const *
will result in two entirely separate pieces of code being generated. It's possible the compiler (or linker) may be able to merge the two after the fact, but not entirely certain (e.g., I've certainly used compilers that didn't).
但最終,模板對速度的積極影響遠多于消極影響.
But in the end, templates have positive effects on speed far more often than negative.
這篇關于C++ 模板會使程序變慢嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!