其他
今日代码大赏 | arrayCopy 优雅使用
数组复制是一项使用频率很高的功能,JDK 中提供了一个高效的 API 来实现它。
下面先让我们来看下官方对这个 API 的解释。
/**
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length)
“如果在应用程序中需要进行数组复制,应该使用这个函数,而不是自己实现。”
下面来举个例子展示下,对于数组复制功能,自己实现和直接调用官方在性能上的差别吧。
自己实现数组复制示例代码:
@Test
public void testArrayCopy(){
int size = 100000;
int[] array = new int[size];
int[] arraydest = new int[size];
for(int i=0;i<array.length;i++){
array[i] = i;
}
long start = System.currentTimeMillis();
for (int k=0;k<1000;k++){
for(int i=0;i<size;i++){
arraydest[i] = array[i];
}
}
long useTime = System.currentTimeMillis()-start;
System.out.println("useTime:"+useTime);
}
运行结果:useTime:102
调用 arrayCopy() 的示例代码:
@Test
public void testArrayCopy(){
int size = 100000;
int[] array = new int[size];
int[] arraydest = new int[size];
for(int i=0;i<array.length;i++){
array[i] = i;
}
long start = System.currentTimeMillis();
for (int k=0;k<1000;k++){
//进行复制
System.arraycopy(array,0,arraydest,0,size);
}
long useTime = System.currentTimeMillis()-start;
System.out.println("useTime:"+useTime);
}
运行结果:useTime:59
通过运行结果可以看出效果,自己实现数组复制,和直接调用官方的性能差别还是挺大的。
因为 System.arraycopy()
函数是 native 函数,通常 native 函数的性能要优于普通函数。
所以仅出于性能考虑,在程序开发时,应尽可能调用 native 函数。
大家感觉今天的代码大赏性能优化技巧如何呢?
欢迎在评论区留下自己的看法。
完整代码片段来源于代码小抄,欢迎点击进入小程序阅读!
在线访问:https://www.codecopy.cn/post/09ncvq
在代码小抄可以看到更多优质代码,也欢迎大家积极分享,可能会获得我们官方的小礼品 🎁~
往期推荐
今日代码大赏 | 优雅提取表达式
今日代码大赏 | 位运算代替乘除法
今日代码大赏 | try-catch 优雅使用
今日代码大赏 | Guava 重试
以上就是本期分享。哝,你们要的封面图(来源于网络),有收获的话记得给我们点赞哦~