System.arraycopy() 分析

来源:互联网 发布:中银淘宝校园卡客服 编辑:程序博客网 时间:2024/05/21 23:15
组里有个同事老用这个System.arraycopy(),我就搞不懂,然后就查了下,然后就知道熟悉底层的人多么幸福了,想用哪个函数就用哪个。。。
来自本人的wordpress博客:

http://www.naitiz.com/index.php/android-quick-tip-use-system-arraycopy_125.html

本文为译文,原文地址 :

http://www.aviyehuda.com/2011/06/android-quick-tip-use-system-arraycopy/

众所周知,使用JNI的方法System.arraycopy()是一种有效数组拷贝的方法,因为它采用native的方式去调用内存,但是这是否同样适用于Android平台呢?如果是这样,那么到底是更有效到什么程度呢?

为了回答这个问题,我做了一个简单的测试运行在PC机和android的activity里面。

下面是PC上的测试代码:

private static final int SIZE_OF_ARRAY = 10000000;
private static long time;

public static void main(String[] args) {

Integer [] sourceArray = new Integer[SIZE_OF_ARRAY];
Integer [] destinationArray = new Integer[SIZE_OF_ARRAY];
fillArray(sourceArray);

startBenchmark();
naiveCopy(sourceArray,destinationArray);
stopBenchmark();

startBenchmark();
System.arraycopy(sourceArray, 0, destinationArray, 0,
sourceArray.length);
stopBenchmark();
}

private static void naiveCopy(Integer [] src, Integer [] dst) {
for (int i = 0; i < src.length; i++) {
dst[i]=src[i];
}

}

private static void fillArray(Integer [] src) {
for (int i = 0; i < src.length; i++) {
src[i]=i;
}

}

private static void startBenchmark() {
time = System.currentTimeMillis();
}

private static void stopBenchmark() {
time = System.currentTimeMillis() - time;
System.out.println( "time="+time);
}

PC机测试结果如下:(java 7, 8GB 内存, CPU intel i5)

Naive algorithm – 14 ms

System.arraycopy(); – 6 ms.

Arraycopy 快了一半的时间。

同样的在android上面测试,代码如下:

public class ArrayCopyTestActivity extends Activity {
private static final int SIZE_OF_ARRAY = 1000000;
private long time;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Integer [] sourceArray = new Integer[SIZE_OF_ARRAY];
Integer [] dst = new Integer[SIZE_OF_ARRAY];
fillArray(sourceArray);

startBenchmark();
naiveCopy(sourceArray,dst);
stopBenchmark();

startBenchmark();
System.arraycopy(sourceArray, 0, dst, 0, sourceArray.length);
stopBenchmark();
}

private void naiveCopy(Integer [] src, Integer [] dst) {
for (int i = 0; i < src.length; i++) {
dst[i]=src[i];
}

}

private void fillArray(Integer [] src) {
for (int i = 0; i < src.length; i++) {
src[i]=i;
}

}

private void startBenchmark() {
time = System.currentTimeMillis();
}

private void stopBenchmark() {
time = System.currentTimeMillis() - time;
Log.d("array copy test", "time="+time);

}
}

*注意,我将数组的长度从1000W缩短至100W,这是因为android平台上允许的内存有限。

nexus 1上得出的运行结果为:

Naive algorithm – 182 ms

System.arraycopy(); – 12 ms.

这个事实意味着在android上使用System.arraycopy()要比普通的数组拷贝快的更多。

总的来说,尽量在android上面去使用System.arraycopy()来代替数组复制吧。

原创粉丝点击