2014-03-04 21 views
6

下面是摘錄自java.util.ArrayList爲什麼java.util.ArrayList中有私有方法outOfBoundsMsg?

/** 
* Constructs an IndexOutOfBoundsException detail message. 
* Of the many possible refactorings of the error handling code, 
* this "outlining" performs best with both server and client VMs. 
*/ 
private String outOfBoundsMsg(int index) { 
    return "Index: "+index+", Size: "+size; 
} 

下面是com.google.collect.Preconditions片斷:

/* 
    * All recent hotspots (as of 2009) *really* like to have the natural code 
    * 
    * if (guardExpression) { 
    * throw new BadException(messageExpression); 
    * } 
    * 
    * refactored so that messageExpression is moved to a separate 
    * String-returning method. 
    * 
    * if (guardExpression) { 
    * throw new BadException(badMsg(...)); 
    * } 
    * 
    * The alternative natural refactorings into void or Exception-returning 
    * methods are much slower. This is a big deal - we're talking factors of 
    * 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer 
    * bug, which should be fixed, but that's a separate, big project). 
    * 
    * The coding pattern above is heavily used in java.util, e.g. in ArrayList. 
    * There is a RangeCheckMicroBenchmark in the JDK that was used to test this. 

五月有人闡明瞭:

  • 爲什麼需要私人outOfBoundsMsg
  • 的「這個意思大綱表現最好......「
  • 我應該開始重構我的代碼以包含字符串返回方法爲我的異常構造函數?的
+2

'outOfBoundsMsg'不是'必需的',Java的開發人員(顯然也是Google Collections)發現他們的庫有足夠的性能改進(可能經過了仔細的測試)。這也是一種優化,可能不適用於所有Java版本和實現。 –

回答

8

,意思是「這個大綱效果最好......」

它的內聯相反的,但不是一個標準術語,這就是爲什麼它被scarequoted。

爲什麼需要私人outOfBoundsMsg

這就是「大綱」即將—提取代碼到一個單獨的方法。

我應該開始重構我的代碼以包含字符串返回異常構造函數的方法嗎?

如果你關心的是每次你拋出一個沒有字符串字面值的異常的話,浪費3納秒,那麼是的。換句話說:NO。

+2

正確:無。如果你不得不問,你沒有充分的理由這樣做。 – keshlam

相關問題