2014-12-19 80 views
-1
 if (x > 5) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 

,我有一個代碼表達式:的代碼執行效率

return (x > 5); 

哪些代碼塊將更加有效地執行 - 或者如果 - else塊或單個返回聲明

回答

3

體面的編譯器會將第一個版本優化成第二個版本。

沒有優化,第一個版本包含一個分支(在x86彙編JXX指令),這是緩慢:

cmp ecx, 5 ; assume ecx contains the value of x 
jle 1f  ; assume x is signed 
mov eax, 1 
ret 
1: 
xor eax, eax 
ret 

第二個版本轉換爲在86一個SETxx指令,這不涉及一個分支,並會更快:

xor eax, eax 
cmp ecx, 5 
setg al 
ret 
+0

好吧好的謝謝... – user3933885 2014-12-19 04:46:44