6

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?
Mark Rotteveel
110k239 gold badges158 silver badges230 bronze badges
asked Mar 4, 2014 at 14:28
1
  • 2
    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. Commented Mar 4, 2014 at 14:41

1 Answer 1

8

meaning 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.

answered Mar 4, 2014 at 14:32

1 Comment

Exactly: NO. If you have to ask, you don't have a good reason for doing so.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.