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:
outOfBoundsMsg
is requiredmeaning of "this outlining performs best..."
It's the opposite of inlining, but not a standard term, which is why it is scarequoted.
why private outOfBoundsMsg is required
That's what "outlining" is about—extracting code to a separate method.
should I start refactoring my code to include string returning methods for my exception constructors?
If you care about 3 nanoseconds wasted each time you throw an exception which does not have a string literal for a message, then yes. In other words: NO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With