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

1

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?
Seventeen answered 4/3, 2014 at 14:28 Comment(1)
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
M
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.

Martita answered 4/3, 2014 at 14:32 Comment(1)
Exactly: NO. If you have to ask, you don't have a good reason for doing so.Josi

© 2022 - 2024 — McMap. All rights reserved.