有时我需要返回空数组来完成一些类合同.
而不是总是创建一个空数组:
@Override public String[] getDescriptionTexts() {
return new String[0]; // no texts
}
Run Code Online (Sandbox Code Playgroud)
我认为从常量中重用一个空数组可能更好:
public class Strings {
public static final String[] EMPTY_ARRAY = new String[0];
}
@Override public String[] getDescriptionTexts() {
return Strings.EMPTY_ARRAY; // no texts
}
Run Code Online (Sandbox Code Playgroud)
这种优化值得吗?
它们在语义上是等价的,它们是可读的,但使用常量数组将(非常轻微)更高效的性能和内存明智.
所以我会选择常数.
一个快速的微观基准测试显示差异在性能方面约为1个cpu周期(0.3纳秒,即没有真正),并且在创建空阵列时GC活动更高(每1000毫秒测试约10毫秒或在GC中花费1%的时间) ).
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2153 次 |
| 最近记录: |