Collection的<T> T[] toArray(T[] a) 性能优化

最近在使用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]);   
        } 
    }   
  
}  

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值