java 提供的System.arrayCopy()方法比自己写的数组copy要快.
查看其源代码:
- public static native void arraycopy(Object src, int srcPos,
- Object dest, int destPos,
- int length);
可以看到被定义为native方法...速度比自己写的普通方法要快.
在jdk1.6中加入了新的数组拷贝方法.Arrays.copyOfRange().
其源代码:
- public static byte[] copyOfRange(byte[] original, int from, int to) {
- int newLength = to - from;
- if (newLength < 0)
- throw new IllegalArgumentException(from &#43; " > " &#43; to);
- byte[] copy &#61; new byte[newLength];
- System.arraycopy(original, from, copy, 0,
- Math.min(original.length - from, newLength));
- return copy;
- }
其实就是System.arraycopy..晕死.
别为做的测试:
- /*******************************************************************************
- *
- * 比较赋值与System.arraycopy谁快
- *
- * 复制的内容越多&#xff0c;System.arraycopy优势更明显
- *
- * Author: Java
- *
- * Modified: 2007.09.16
- *
- ******************************************************************************/
- public final class WhoFaster
- {
- public static void main( String[] args )
- {
- /*/
- int begin&#61;100;
- int length&#61;12;
- String temp&#61;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890";
- int times&#61;10000000; //千万
- /*/
- int begin&#61;100;
- int length&#61;120;
- String temp&#61;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"黑客帝国忍者神龟变形金刚"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890"
- &#43;"12345678901234567890";
- int times&#61;1000000; //百万
- //*/
- char[] oldArray&#61;temp.toCharArray();
- char[] newArray&#61;null;
- long start&#61;0L;
- //
- // 单纯赋值
- //
- newArray&#61;new char[length];
- start&#61;System.currentTimeMillis();
- for( int i&#61;0; i
- {
- for( int j&#61;0; j
- {
- newArray[j]&#61;oldArray[begin&#43;j];
- }
- }
- System.out.println( new String( newArray )&#43;" "&#43;( System.currentTimeMillis()-start ) );
- //
- // System.arraycopy
- //
- newArray&#61;new char[length];
- start&#61;System.currentTimeMillis();
- for( int i&#61;0; i
- {
- System.arraycopy( oldArray, begin, newArray, 0, length );
- }
- System.out.println( new String( newArray )&#43;" "&#43;( System.currentTimeMillis()-start ) );
- }
- }
其结论:
在第一种情况&#xff0c;循环千万&#xff0c;一个900&#xff0c;一个1000&#xff0c;两者相差100毫秒
第二种情况就拉大了&#xff0c;循环千万&#xff0c;一个6700&#xff0c;一个2200&#xff0c;相差4500毫秒
为防止JVM将字符数组作为常量保存在内存中&#xff0c;我分别屏蔽运行&#xff0c;效果一样。
也就是说&#xff0c;对于很短的字符串复制&#xff0c;单纯赋值略快&#xff0c;可以忽略
对于很长的字符串复制&#xff0c;用单纯赋值就是脏代码