Here's snippet from 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;
}
Here's snippet from 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.
May somebody shed light on:
- why private
outOfBoundsMsg
is required - meaning of "this outlining performs best..."
- should I start refactoring my code to include string returning methods for my exception constructors?
outOfBoundsMsg
is not 'required', the developers of Java (and apparently also Google Collections) found it was a sufficient performance improvement for their library (probably after careful testing). It is also an optimization that might not work with all Java versions and implementations. – Valdemar