是否值得为Java中的空数组创建常量?

时间:2014-11-27 09:32:52

标签: 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[] getDescriptionTexts() {
    return Strings.EMPTY_ARRAY; // no texts
}

这种优化值得吗?

3 个答案:

答案 0 :(得分:8)

它们在语义上是等价的,它们是可读的,但使用常量数组将(非常轻微)更高效的性能和内存。

所以我会选择常数。


一个快速微观基准测试表明,在性能方面差异大约是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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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