On Thu, 2 Jun 2022 21:48:07 GMT, Sergey Bylokhov <s...@openjdk.org> wrote:
>>> BTW I think that the usage of >>> `return icons.toArray(EMPTY_TRAY_ARRAY);` >>> is slower than any of other cases: presized or zero. So if we would like to >>> use a similar pattern the zero version is better. >> >> Why is it? It's the same as `icons.toArray(new TrayIcon[0])` without >> creating a new zero-sized array. > > It should be checked of course, but in zero case the size is known by the > compiler not sure that in the cached case it can make the same optimizations. > The article above said the cached case is a "marginal improvement over new > Foo[0]" I'm unsure if the Java compiler performs any optimisations here. The called `toArray` verifies the size first, and it's the same size either way, which is zero. If there were no pre-allocated array, I wouldn't bother with a cached copy. But we have one. One less object to be allocated and to be garbage-collected. Since the number of the icons is unlikely to become large, I doubt there'll be any noticeable difference. As your sample above demonstrates, the old code could return an array with a null element in it. This is resolved by the new code. ------------- PR: https://git.openjdk.java.net/jdk/pull/8850