在Java中为空数组设置一个常量是否值得?

在Java中为空数组设置一个常量是否值得?,java,Java,有时我需要返回空数组来完成一些类契约 不要总是创建空数组: @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

有时我需要返回空数组来完成一些类契约

不要总是创建空数组:

@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
}

这种优化值得吗?

他们没有在JDK中包含很多有用的东西。空字符串怎么样?听起来也很有用


我个人倾向于使用第二种方法,即定义
静态最终字符串[]EMPTY=新字符串[0]
,然后使用它

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

它们在语义上是等价的,可读性相同,但使用常量数组将(稍微)提高性能和内存效率

所以我只想求常数


一个快速的微基准测试表明,性能上的差异大约为1个cpu周期(0.3纳秒,也就是说,实际上什么都没有),并且空阵列创建时GC活动更高(每1000毫秒测试约10毫秒或GC时间的1%)


两种代码在性能方面没有差异。你不会注意到任何区别。内存分配呢?绝对值得。没有理由不使用常量。该常量的可能副本更为持久,但有更好的答案和基准。如果应用程序长时间运行,每次需要创建数组都会导致额外的GC活动,从而降低性能+1@AlexR出于好奇,我还检查了GC的影响-它没有那么高(cpu时间的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