From 3641f1626df6b9b1c11dd3f16b01a01495f4662d Mon Sep 17 00:00:00 2001 From: Lars Grefer Date: Sat, 15 Aug 2020 16:30:09 +0200 Subject: Collection.toArray() call style There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]). In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. Signed-off-by: Lars Grefer --- .../src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java | 2 +- .../src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'bcel-builder') diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java index bb42a07ee..014ad558d 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java @@ -741,7 +741,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { for (clazz = clazz.getSuperClass(); clazz != null; clazz = clazz.getSuperClass()) { vec.add(clazz); } - return vec.toArray(new JavaClass[vec.size()]); + return vec.toArray(new JavaClass[0]); } /** diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java index 371013997..03c7c716b 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java @@ -196,7 +196,7 @@ public class ClassGen extends Modifiers implements Cloneable { ConstantPool cp = this.cpool.getFinalConstantPool(); return new JavaClass(classnameIndex, superclassnameIndex, filename, major, minor, modifiers, cp, interfaces, fields, - methods, attributes.toArray(new Attribute[attributes.size()]));// OPTIMIZE avoid toArray()? + methods, attributes.toArray(new Attribute[0]));// OPTIMIZE avoid toArray()? } public void addInterface(String name) { -- cgit v1.2.3