最近在使用PMD进行代码缺陷扫描时,有一类问题PMD称为"call to Collection.toArray() may be optimizable"
下面一行为问题代码:
result = (IResearch[]) list.toArray(new IResearch[0]);
PMD对这类问题给出的解决方案如下:
class Foo { void bar(Collection x) { // A bit inefficient x.toArray(new Foo[0]); // Much better; this one sizes the destination array, avoiding // a reflection call in some Collection implementations x.toArray(new Foo[x.size()]); } }
再看下ArrayList的<T> T[] toArray(T[] a) 源码:
public <T> T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array. newInstance(a.getClass().getComponentType(), size); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
你就发现如果采用大家常用的把a的length设为0,就需要反射API来创建一个大小为size的数组,而这对性能有一定的影响.
所以最好的方式就是直接把a的length设为Collection的size从而避免调用反射API来达到一定的性能优化.
import java.util.ArrayList; public class ToArrayTest { public static void main(String[] args) { ArrayList al = new ArrayList(); for (int i = 0; i < 10; i++) { al.add(String.valueOf(i)); } String[] s1 = (String[]) al.toArray(new String[15]); for (int i = 0; i < s1.length; i++) { System.out.println(i+","+s1[i]); } String[] s2 = (String[]) al.toArray(new String[5]); for (int i = 0; i < s2.length; i++) { System.out.println(i+","+s2[i]); } System.out.println("OptimizableToArrayCall"); String[] s3 = (String[]) al.toArray(new String[al.size()]); for (int i = 0; i < s3.length; i++) { System.out.println(i+","+s3[i]); } } }