【问题标题】:Is it worth to make a constant for an empty array in Java? [duplicate]是否值得在 Java 中为空数组创建一个常量? [复制]
【发布时间】:2014-11-27 09:32:51
【问题描述】:

有时我需要返回空数组来履行一些类合同。

而不是总是创建一个空数组:

@Override public String[] getDescriptionTexts() {
    return new String[0]; // no texts
}

我认为重用常量中的空数组可能会更好:

public class Strings {
    public static final String[] EMPTY_ARRAY = new String[0];
}

@Override public String[] getDescriptionTexts() {
    return Strings.EMPTY_ARRAY; // no texts
}

这种优化值得吗?

【问题讨论】:

标签: java


【解决方案1】:

它们在语义上是等价的,它们同样具有可读性,但使用常量数组会(非常轻微地)提高性能和内存效率。

所以我会选择常数。


一个快速的微型基准测试表明,在性能方面的差异大约是 1 个 cpu 周期(0.3 纳秒,即没有什么),并且在创建空数组时 GC 活动更高(每 1000 毫秒测试约 10 毫秒或 1% 的时间在 GC 上花费)。

Benchmark                                       Mode  Samples    Score   Error   Units

c.a.p.SO27167199.constant                       avgt       10    3.165 ± 0.026   ns/op
c.a.p.SO27167199.constant:@gc.count.profiled    avgt       10    0.000 ±   NaN  counts
c.a.p.SO27167199.constant:@gc.count.total       avgt       10    0.000 ±   NaN  counts
c.a.p.SO27167199.constant:@gc.time.profiled     avgt       10    0.000 ±   NaN      ms
c.a.p.SO27167199.constant:@gc.time.total        avgt       10    0.000 ±   NaN      ms

c.a.p.SO27167199.newArray                       avgt       10    3.405 ± 0.051   ns/op
c.a.p.SO27167199.newArray:@gc.count.profiled    avgt       10  250.000 ±   NaN  counts
c.a.p.SO27167199.newArray:@gc.count.total       avgt       10  268.000 ±   NaN  counts
c.a.p.SO27167199.newArray:@gc.time.profiled     avgt       10   95.000 ±   NaN      ms
c.a.p.SO27167199.newArray:@gc.time.total        avgt       10  108.000 ±   NaN      ms

【讨论】:

  • 每次需要时创建数组会导致额外的 GC 活动,如果应用程序运行很长时间,可能会降低性能。 +1
  • @AlexR 出于好奇,我还检查了 GC 的影响 - 它不是那么高(CPU 时间的 1%),但也不容忽视。
  • GC 影响取决于创建的此类数组的数量。如果此代码位于性能关键路径上,则此影响可能很显着。
【解决方案2】:

是的,如果您需要在 Java 中多次使用空数组或空字符串,使用常量是一个更好的主意。如果你使用单个静态常量,它只会在内存中创建一个对象,多次创建同一个对象。

【讨论】:

    【解决方案3】:

    他们没有包含很多对 JDK 有用的东西。 EMPTY_STRING 呢?听起来也很有用。

    我个人倾向于使用您的第二种方法,即定义static final String[] EMPTY = new String[0],然后使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2023-03-10
      • 2019-09-06
      相关资源
      最近更新 更多