下面是摘錄自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
- 的「這個意思大綱表現最好......「
- 我應該開始重構我的代碼以包含字符串返回方法爲我的異常構造函數?的
'outOfBoundsMsg'不是'必需的',Java的開發人員(顯然也是Google Collections)發現他們的庫有足夠的性能改進(可能經過了仔細的測試)。這也是一種優化,可能不適用於所有Java版本和實現。 –