Is it worth to make a constant for an empty array in Java? -
sometimes need return empty arrays fulfill classes contracts.
instead of creating empty array:
@override public string[] getdescriptiontexts() { return new string[0]; // no texts }
i think may better re-use empty array constant:
public class strings { public static final string[] empty_array = new string[0]; } @override public string[] getdescriptiontexts() { return strings.empty_array; // no texts }
is kind of optimization worth it?
they semantically equivalent, readable, using constant array (very slightly) more efficient performance , memory wise.
so go constant.
a quick micro benchmark shows difference 1 cpu cycle in terms of performance (0.3 nanoseconds, i.e. nothing really) , gc activity higher empty array creation (~10ms per 1000ms test or 1% of time spend in 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
Comments
Post a Comment