【问题标题】:Why is there private method outOfBoundsMsg in java.util.ArrayList?为什么 java.util.ArrayList 中有私有方法 outOfBoundsMsg?
【发布时间】:2014-04-06 03:34:46
【问题描述】:

这是来自java.util.ArrayList的sn-p:

/**
 * 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;
}

这是来自com.google.collect.Preconditions的sn-p:

  /*
   * 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.

希望有人能解释一下:

  • 为什么需要私人outOfBoundsMsg
  • “此大纲表现最佳……”的含义
  • 我是否应该开始重构我的代码以包含用于我的异常构造函数的字符串返回方法?

【问题讨论】:

  • outOfBoundsMsg 不是“必需的”,Java 的开发人员(显然还有 Google Collections)发现这对于他们的库来说是一个足够的性能改进(可能经过仔细测试)。它也是一种优化,可能不适用于所有 Java 版本和实现。

标签: java arraylist exception-handling guava jvm-hotspot


【解决方案1】:

“这个大纲表现最好……”的意思

它与内联相反,但不是标准术语,这就是它被吓到的原因。

为什么需要私有 outOfBoundsMsg

这就是“大纲”的含义——将代码提取到单独的方法中。

我应该开始重构我的代码,为我的异常构造函数包含字符串返回方法吗?

如果您关心每次抛出一个没有字符串文字的消息的异常时浪费 3 纳秒,那么可以。换句话说:没有。

【讨论】:

  • 完全正确:不。如果你不得不问,你没有充分的理由这样做。
猜你喜欢
  • 2021-07-22
  • 2011-03-07
  • 1970-01-01
  • 2010-10-27
  • 2010-09-09
  • 2018-05-16
  • 2015-04-16
相关资源
最近更新 更多