Inline Functions
內聯函數
▽Define functions inline only when they are small, say, 10 lines or less.
只有函數非常小,10行以內才定義為內聯。
Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism.
定義:一種函數調用機制,你將函數聲明為內聯,編譯器會將整個函數體在調用處展開。
Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions.
前題條件:當內聯一個很小函數時會產生更有效率的代碼,考慮類成員訪問函數或其他短小,性能要求嚴格的函數。
Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache.
限制:過度使用內聯函數實際上會使減慢程序運行,取決於函數體大小,它決定了代碼增加或減少。內聯一個非常小成員訪問函數會減少代碼,而內聯一個非常大的函數代碼會戲劇性的增長。在現代處理器上由於廣泛使用指令緩存,小代碼通常會運行得更快。
Decision:
決策:
A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls!
一個合適的經驗法則:不要內聯一個超過10行函數,但要小心析構函數,它並沒有表面看上去那麼小,因為它會調用類成員和基類的析構函數。 www.2cto.com
Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed).
其他有用的經驗法則:一個函數如果有判斷或循環語句通常是沒效率的。(除非在通常的情況下循環語句或判斷語句不會執行)。
It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators.
知道哪些函數即使你聲明了內聯也不會內聯很重要:比如說虛函數和遞歸函數在一般情況下不會內聯。通常情況下遞歸函數不應內聯。使虛函數內聯的主要原因在於類定義,主要是方便的原因,比如說成員訪問函數。