【发布时间】:2014-04-06 03:34:46
【问题描述】:
这是来自java.util.ArrayList的sn-p:
/**
* 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的sn-p:
/*
* 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 版本和实现。
标签: java arraylist exception-handling guava jvm-hotspot