System.arraycopy

其中 Arrays.copy是JDK1.6中引用的新方法。它调用了System.arraycopy完成相关数组的复制。

在JDK1.6中ArrayList的相关add remove等操作都是调用System.arraycopy来对其底层的Object[]elementData数组进行操作的。

LinkedList则使用一个Entry的内部类,其有指向next和previous的引用保存元素,它的遍历则先计算出所需index和size>>1(以为后的大小),确定是通过previous还是next遍历。

System.arraycopy

 

Java代码   收藏代码
  1. 01.public static void arraycopy(Object src,     
  2. 02.                             int srcPos,     
  3. 03.                             Object dest,     
  4. 04.                             int destPos,     
  5. 05.                             int length)     
  6. 06.    从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。被复制的组件的编号等于 length 参数。源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。  
  7.   
  8. 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/yangqillohe/archive/2010/05/26/5625159.aspx  

 

它是个native方法,测试结果表明,

当数组很小,但存是调用次数多的话。

使用它复制数组并不比for循环手工复制数组快。

 

Java代码   收藏代码
  1. int count = 10000000;     
  2.         long start = System.currentTimeMillis();     
  3.         for (int i = 0; i < count; i++) {     
  4.             System.arraycopy(intArray1, 0, intArray2, 0, intArray1.length);     
  5.         }     
  6.         long end = System.currentTimeMillis() - start;     
  7.         System.out.println("use " + end);     
  8.         long start2 = System.currentTimeMillis();     
  9.         for (int i = 0; i < count; i++) {     
  10.             for (int j = 0; j < intArray1.length; j++) {     
  11.                 intArray2[j] = intArray1[j];     
  12.             }     
  13.         }     
  14.         long end2 = System.currentTimeMillis() - start2;     
  15.         System.out.println("use " + end2);    
  16. int count = 10000000;  
  17.         long start = System.currentTimeMillis();  
  18.         for (int i = 0; i < count; i++) {  
  19.             System.arraycopy(intArray1, 0, intArray2, 0, intArray1.length);  
  20.         }  
  21.         long end = System.currentTimeMillis() - start;  
  22.         System.out.println("use " + end);  
  23.         long start2 = System.currentTimeMillis();  
  24.         for (int i = 0; i < count; i++) {  
  25.             for (int j = 0; j < intArray1.length; j++) {  
  26.                 intArray2[j] = intArray1[j];  
  27.             }  
  28.         }  
  29.         long end2 = System.currentTimeMillis() - start2;  
  30.         System.out.println("use " + end2);   
  31.   
  32. use 224    
  33. use 105    

 

 

但是如果是数组比较大,那么使用System.arraycopy会比较有优势,因为其使用的是内存复制,省去了大量的数组寻址访问等时间。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值