對於簡單比較運算,**效能差異可忽略不計**。編譯器優化(-O2/-O3)常會自動內聯小函數,消除呼叫開銷。
push。call:壓入返回位址 (EIP),跳轉函數入口。push ebp; mov ebp, esp; sub esp, N (3 條指令)。leave; ret (2 條指令),恢復棧與 EIP。共計 **6+ 條指令** + 參數壓棧。若參數為結構體,還需 memcpy 複製,開銷顯著增加。
// 測試框架
#include
void inline_compare(int* a, int n) { /* 直接在 main 迴圈比較 */ }
void func_compare(int* a, int n) { /* 獨立函數 */ }
int main() {
clock_t t1 = clock();
for (int i=0; i<1e8; ++i) inline_compare(arr, 10);
clock_t t2 = clock();
for (int i=0; i<1e8; ++i) func_compare(arr, 10);
clock_t t3 = clock();
printf("inline: %ld, func: %ld\n", t2-t1, t3-t2);
}
開啟 -O2 後兩者通常持平。
正常應用層開發,**可讀性、模組化優先**。若性能分析 (profiling) 指出特定函數為熱點,再考慮 inline、宏、或手動展開。過早優化是萬惡之源。