這兩個代碼之間存在相當大的優化差異(在Java和/或C++中,當前,即使我猜它在每種語言中都是一樣的)?還是僅僅是代碼可讀性問題?使用多個返回語句
int foo(...) {
if (cond) {
if (otherCondA)
return 1;
if (otherCondB)
return 2;
return 3;
}
int temp = /* context and/or param-dependent */;
if (otherCondA)
return 4 * temp;
if (otherCondB)
return 4/temp;
return 4 % temp;
}
和
int foo(...) {
int value = 0;
if (cond) {
if (otherCondA)
value = 1;
else if (otherCondB)
value = 2;
else value = 3;
}
else {
int temp = /* context and/or param-dependent */;
if (otherCondA)
value = 4 * temp;
else if (otherCondB)
value = 4/temp;
else
value = 4 % temp;
}
return value;
}
第一個是短,避免else語句的多個鱗狀部,節約一個變量(或者至少看起來這樣做),但我不知道它真的改變了一些東西...
你不確定這是個好主意......爲什麼?你有沒有任何理性的原因呢?或者你今天早上醒來就是這樣嗎?您是否嘗試檢查生成的代碼或使用分析工具? – 2014-10-06 16:51:41
許多人主張單一'返回',因爲他們認爲代碼更容易通過。即使我遵循這個建議,當前提條件失敗時,我也允許在函數前面提前返回。 – 2014-10-06 17:09:41
經過幾次測試之後,編譯器只能優化MarkRansom談到的多重返回語句的種類。在函數中間,優化非常差。 – 2014-10-06 17:28:19