Replace toArray(new T[size]) with toArray(new T[0]) to eliminate zero-out and allow the VM to optimize. (#8075)

Motivation:

Using toArray(new T[0]) is usually the faster aproach these days. We should use it.

See also https://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion.

Modifications:

Replace toArray(new T[size]) with toArray(new T[0]).

Result:

Faster code.
This commit is contained in:
Norman Maurer 2018-06-29 07:56:04 +02:00 committed by GitHub
parent c321e8ea4a
commit 83710cb2e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 41 additions and 42 deletions

View File

@ -391,7 +391,7 @@ public class CompositeByteBuf extends AbstractReferenceCountedByteBuf implements
}
Collection<ByteBuf> col = (Collection<ByteBuf>) buffers;
return addComponents0(increaseIndex, cIndex, col.toArray(new ByteBuf[col.size()]), 0 , col.size());
return addComponents0(increaseIndex, cIndex, col.toArray(new ByteBuf[0]), 0 , col.size());
}
/**
@ -1507,7 +1507,7 @@ public class CompositeByteBuf extends AbstractReferenceCountedByteBuf implements
i ++;
}
return buffers.toArray(new ByteBuffer[buffers.size()]);
return buffers.toArray(new ByteBuffer[0]);
}
/**

View File

@ -593,7 +593,7 @@ final class FixedCompositeByteBuf extends AbstractReferenceCountedByteBuf {
s = buffer(++i);
}
return array.toArray(new ByteBuffer[array.size()]);
return array.toArray(new ByteBuffer[0]);
} finally {
array.recycle();
}

View File

@ -87,7 +87,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
buffers.add(EMPTY_BUFFER);
}
ByteBuf buffer = wrappedBuffer(Integer.MAX_VALUE, buffers.toArray(new ByteBuf[buffers.size()])).order(order);
ByteBuf buffer = wrappedBuffer(Integer.MAX_VALUE, buffers.toArray(new ByteBuf[0])).order(order);
// Truncate to the requested capacity.
buffer.capacity(length);

View File

@ -161,7 +161,7 @@ public final class ClientCookieEncoder extends CookieEncoder {
if (cookies.size() == 1) {
encode(buf, cookies.iterator().next());
} else {
Cookie[] cookiesSorted = cookies.toArray(new Cookie[cookies.size()]);
Cookie[] cookiesSorted = cookies.toArray(new Cookie[0]);
Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
for (Cookie c : cookiesSorted) {
encode(buf, c);
@ -198,7 +198,7 @@ public final class ClientCookieEncoder extends CookieEncoder {
while (cookiesIt.hasNext()) {
cookiesList.add(cookiesIt.next());
}
Cookie[] cookiesSorted = cookiesList.toArray(new Cookie[cookiesList.size()]);
Cookie[] cookiesSorted = cookiesList.toArray(new Cookie[0]);
Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
for (Cookie c : cookiesSorted) {
encode(buf, c);

View File

@ -1515,6 +1515,6 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
}
}
values.add(svalue.substring(start));
return values.toArray(new String[values.size()]);
return values.toArray(new String[0]);
}
}

View File

@ -232,7 +232,7 @@ public class DefaultHttpHeadersTest {
.add(HttpHeaderNames.CONTENT_LENGTH, 10)
.names();
String[] namesArray = nettyHeaders.toArray(new String[nettyHeaders.size()]);
String[] namesArray = nettyHeaders.toArray(new String[0]);
assertArrayEquals(namesArray, new String[] { HttpHeaderNames.CONTENT_LENGTH.toString() });
}

View File

@ -1115,7 +1115,7 @@ public final class AsciiString implements CharSequence, Comparable<CharSequence>
}
}
return res.toArray(new AsciiString[res.size()]);
return res.toArray(new AsciiString[0]);
}
/**

View File

@ -78,7 +78,7 @@ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecut
}
final ScheduledFutureTask<?>[] scheduledTasks =
scheduledTaskQueue.toArray(new ScheduledFutureTask<?>[scheduledTaskQueue.size()]);
scheduledTaskQueue.toArray(new ScheduledFutureTask<?>[0]);
for (ScheduledFutureTask<?> task: scheduledTasks) {
task.cancelWithoutRemove(false);

View File

@ -62,7 +62,7 @@ public class FastThreadLocal<V> {
@SuppressWarnings("unchecked")
Set<FastThreadLocal<?>> variablesToRemove = (Set<FastThreadLocal<?>>) v;
FastThreadLocal<?>[] variablesToRemoveArray =
variablesToRemove.toArray(new FastThreadLocal[variablesToRemove.size()]);
variablesToRemove.toArray(new FastThreadLocal[0]);
for (FastThreadLocal<?> tlv: variablesToRemoveArray) {
tlv.remove(threadLocalMap);
}

View File

@ -75,7 +75,7 @@ public class ConstantPoolTest {
set.add(d);
set.add(a);
TestConstant[] array = set.toArray(new TestConstant[5]);
TestConstant[] array = set.toArray(new TestConstant[0]);
assertThat(array.length, is(5));
// Sort by name

View File

@ -71,7 +71,7 @@ abstract class ConscryptAlpnSslEngine extends JdkSslEngine {
}
// Set the list of supported ALPN protocols on the engine.
Conscrypt.setApplicationProtocols(engine, protocols.toArray(new String[protocols.size()]));
Conscrypt.setApplicationProtocols(engine, protocols.toArray(new String[0]));
}
/**

View File

@ -46,8 +46,8 @@ public final class IdentityCipherSuiteFilter implements CipherSuiteFilter {
Set<String> supportedCiphers) {
if (ciphers == null) {
return defaultToDefaultCiphers ?
defaultCiphers.toArray(new String[defaultCiphers.size()]) :
supportedCiphers.toArray(new String[supportedCiphers.size()]);
defaultCiphers.toArray(new String[0]) :
supportedCiphers.toArray(new String[0]);
} else {
List<String> newCiphers = new ArrayList<String>(supportedCiphers.size());
for (String c : ciphers) {
@ -56,7 +56,7 @@ public final class IdentityCipherSuiteFilter implements CipherSuiteFilter {
}
newCiphers.add(c);
}
return newCiphers.toArray(new String[newCiphers.size()]);
return newCiphers.toArray(new String[0]);
}
}
}

View File

@ -84,7 +84,7 @@ public class JdkSslContext extends SslContext {
"TLSv1.2", "TLSv1.1", "TLSv1");
if (!protocols.isEmpty()) {
DEFAULT_PROTOCOLS = protocols.toArray(new String[protocols.size()]);
DEFAULT_PROTOCOLS = protocols.toArray(new String[0]);
} else {
DEFAULT_PROTOCOLS = engine.getEnabledProtocols();
}

View File

@ -438,7 +438,7 @@ public final class OpenSsl {
libNames.add(staticLibName);
NativeLibraryLoader.loadFirstAvailable(SSL.class.getClassLoader(),
libNames.toArray(new String[libNames.size()]));
libNames.toArray(new String[0]));
}
private static boolean initializeTcNative(String engine) throws Exception {

View File

@ -98,7 +98,7 @@ final class PemReader {
throw new CertificateException("found no certificates in input stream");
}
return certs.toArray(new ByteBuf[certs.size()]);
return certs.toArray(new ByteBuf[0]);
}
static ByteBuf readPrivateKey(File file) throws KeyException {

View File

@ -246,7 +246,7 @@ public final class ReferenceCountedOpenSslClientContext extends ReferenceCounted
final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
try {
final Set<String> keyTypesSet = supportedClientKeyTypes(keyTypeBytes);
final String[] keyTypes = keyTypesSet.toArray(new String[keyTypesSet.size()]);
final String[] keyTypes = keyTypesSet.toArray(new String[0]);
final X500Principal[] issuers;
if (asn1DerEncodedPrincipals == null) {
issuers = null;

View File

@ -265,7 +265,7 @@ public abstract class ReferenceCountedOpenSslContext extends SslContext implemen
List<String> nextProtoList = apn.protocols();
/* Set next protocols for next protocol negotiation extension, if specified */
if (!nextProtoList.isEmpty()) {
String[] appProtocols = nextProtoList.toArray(new String[nextProtoList.size()]);
String[] appProtocols = nextProtoList.toArray(new String[0]);
int selectorBehavior = opensslSelectorFailureBehavior(apn.selectorFailureBehavior());
switch (apn.protocol()) {

View File

@ -1286,7 +1286,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
@Override
public final String[] getSupportedCipherSuites() {
return OpenSsl.AVAILABLE_CIPHER_SUITES.toArray(new String[OpenSsl.AVAILABLE_CIPHER_SUITES.size()]);
return OpenSsl.AVAILABLE_CIPHER_SUITES.toArray(new String[0]);
}
@Override
@ -1359,7 +1359,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
@Override
public final String[] getSupportedProtocols() {
return OpenSsl.SUPPORTED_PROTOCOLS_SET.toArray(new String[OpenSsl.SUPPORTED_PROTOCOLS_SET.size()]);
return OpenSsl.SUPPORTED_PROTOCOLS_SET.toArray(new String[0]);
}
@Override
@ -1373,7 +1373,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
if (!isDestroyed()) {
opts = SSL.getOptions(ssl);
} else {
return enabled.toArray(new String[1]);
return enabled.toArray(new String[0]);
}
}
if (isProtocolEnabled(opts, SSL.SSL_OP_NO_TLSv1, PROTOCOL_TLS_V1)) {
@ -1391,7 +1391,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
if (isProtocolEnabled(opts, SSL.SSL_OP_NO_SSLv3, PROTOCOL_SSL_V3)) {
enabled.add(PROTOCOL_SSL_V3);
}
return enabled.toArray(new String[enabled.size()]);
return enabled.toArray(new String[0]);
}
private static boolean isProtocolEnabled(int opts, int disableMask, String protocolString) {
@ -1955,7 +1955,7 @@ public class ReferenceCountedOpenSslEngine extends SSLEngine implements Referenc
if (values == null || values.isEmpty()) {
return EmptyArrays.EMPTY_STRINGS;
}
return values.keySet().toArray(new String[values.size()]);
return values.keySet().toArray(new String[0]);
}
private void notifyUnbound(Object value, String name) {

View File

@ -53,7 +53,7 @@ public final class SupportedCipherSuiteFilter implements CipherSuiteFilter {
newCiphers.add(c);
}
}
return newCiphers.toArray(new String[newCiphers.size()]);
return newCiphers.toArray(new String[0]);
}
}

View File

@ -172,7 +172,7 @@ public final class FingerprintTrustManagerFactory extends SimpleTrustManagerFact
list.add(f.clone());
}
this.fingerprints = list.toArray(new byte[list.size()][]);
this.fingerprints = list.toArray(new byte[0][]);
}
private static byte[][] toFingerprintArray(Iterable<String> fingerprints) {
@ -197,7 +197,7 @@ public final class FingerprintTrustManagerFactory extends SimpleTrustManagerFact
list.add(StringUtil.decodeHexDump(f));
}
return list.toArray(new byte[list.size()][]);
return list.toArray(new byte[0][]);
}
@Override

View File

@ -350,7 +350,7 @@ public class OpenSslEngineTest extends SSLEngineTest {
srcsLen += dup.capacity();
}
ByteBuffer[] srcs = srcList.toArray(new ByteBuffer[srcList.size()]);
ByteBuffer[] srcs = srcList.toArray(new ByteBuffer[0]);
ByteBuffer dst = allocateBuffer(
unwrapEngine(clientEngine).maxEncryptedPacketLength() - 1);

View File

@ -93,8 +93,7 @@ public abstract class AbstractMicrobenchmarkBase {
}
}
if (jvmArgs.length != customArgs.size()) {
jvmArgs = new String[customArgs.size()];
customArgs.toArray(jvmArgs);
jvmArgs = customArgs.toArray(new String[0]);
}
return jvmArgs;
}

View File

@ -142,7 +142,7 @@ public final class DefaultDnsServerAddressStreamProvider implements DnsServerAdd
}
DEFAULT_NAME_SERVER_LIST = Collections.unmodifiableList(defaultNameServers);
DEFAULT_NAME_SERVER_ARRAY = defaultNameServers.toArray(new InetSocketAddress[defaultNameServers.size()]);
DEFAULT_NAME_SERVER_ARRAY = defaultNameServers.toArray(new InetSocketAddress[0]);
DEFAULT_NAME_SERVERS = sequential(DEFAULT_NAME_SERVER_ARRAY);
}

View File

@ -131,7 +131,7 @@ public class DnsNameResolver extends InetNameResolver {
@SuppressWarnings("unchecked")
List<String> list = (List<String>) nameservers.invoke(instance);
searchDomains = list.toArray(new String[list.size()]);
searchDomains = list.toArray(new String[0]);
} catch (Exception ignore) {
// Failed to get the system name search domain list.
searchDomains = EmptyArrays.EMPTY_STRINGS;

View File

@ -335,7 +335,7 @@ public final class DnsNameResolverBuilder {
list.add(f);
}
this.searchDomains = list.toArray(new String[list.size()]);
this.searchDomains = list.toArray(new String[0]);
return this;
}

View File

@ -187,7 +187,7 @@ public abstract class DnsServerAddresses {
throw new IllegalArgumentException("empty addresses");
}
return list.toArray(new InetSocketAddress[list.size()]);
return list.toArray(new InetSocketAddress[0]);
}
private static InetSocketAddress[] sanitize(InetSocketAddress[] addresses) {
@ -210,7 +210,7 @@ public abstract class DnsServerAddresses {
return defaultAddressArray();
}
return list.toArray(new InetSocketAddress[list.size()]);
return list.toArray(new InetSocketAddress[0]);
}
/**

View File

@ -67,7 +67,7 @@ class TestDnsServer extends DnsServer {
BYTES.put("0:1:1:1:1:1:1:1", new byte[]{0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1});
BYTES.put("1:1:1:1:1:1:1:1", new byte[]{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1});
IPV6_ADDRESSES = BYTES.keySet().toArray(new String[BYTES.size()]);
IPV6_ADDRESSES = BYTES.keySet().toArray(new String[0]);
}
private final RecordStore store;

View File

@ -102,7 +102,7 @@ public abstract class AddressResolverGroup<T extends SocketAddress> implements C
public void close() {
final AddressResolver<T>[] rArray;
synchronized (resolvers) {
rArray = (AddressResolver<T>[]) resolvers.values().toArray(new AddressResolver[resolvers.size()]);
rArray = (AddressResolver<T>[]) resolvers.values().toArray(new AddressResolver[0]);
resolvers.clear();
}

View File

@ -172,7 +172,7 @@ public class CaliperMeasure {
}
private static MeasurementSet measurementSet(final Map<Long, Measurement> map) {
final Measurement[] array = map.values().toArray(new Measurement[map.size()]);
final Measurement[] array = map.values().toArray(new Measurement[0]);
return new MeasurementSet(array);
}

View File

@ -160,10 +160,10 @@ public class ServerBootstrap extends AbstractBootstrap<ServerBootstrap, ServerCh
final Entry<ChannelOption<?>, Object>[] currentChildOptions;
final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
synchronized (childOptions) {
currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
}
synchronized (childAttrs) {
currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
}
p.addLast(new ChannelInitializer<Channel>() {