Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there private method outOfBoundsMsg in java.util.ArrayList?

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?
like image 435
aasu Avatar asked Mar 04 '14 14:03

aasu


1 Answers

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.

like image 71
Marko Topolnik Avatar answered Sep 20 '22 10:09

Marko Topolnik