这里的片段来自java.util.ArrayList
:
/** * 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
需要私人
"这个概述表现得最好......"的含义
我应该开始重构我的代码以包含我的异常构造函数的字符串返回方法吗?
Marko Topoln.. 8
"这个概述表现得最好......"的含义
它与内联相反,但不是标准术语,这就是它被吓唬的原因.
为什么私有outOfBoundsMsg是必需的
这就是"概述"即将代码提取到单独的方法.
我应该开始重构我的代码以包含我的异常构造函数的字符串返回方法吗?
如果你在每次抛出一个没有字符串文字的异常时浪费3纳秒,那么是的.换句话说:不.