.clone()或Arrays.copyOf()? [英] .clone() or Arrays.copyOf()?
本文介绍了.clone()或Arrays.copyOf()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了减少可变性,我们是否应该使用
In an effort to reduce mutability, should we rather use
public void setValues(String[] newVals) {
this.vals = ( newVals == null ? null : newVals.clone() );
}
或
public void setValues(String[] newVals) {
this.vals = ( newVals == null ? null : Arrays.copyOf(newVals, newVals.length) );
}
推荐答案
使用jmh更新
使用jmh ,我得到类似的结果,除了克隆
似乎稍微好一点。
Update using jmh
Using jmh, I get similar results, except that clone
seems to be marginally better.
我跑了快速测试性能: clone
, System.arrayCopy
和 Arrays.copyOf
具有非常相似的性能(jdk 1.7.06,服务器vm)。
I ran a quick test for performance: clone
, System.arrayCopy
and Arrays.copyOf
have very similar performance (jdk 1.7.06, server vm).
有关详情(以毫秒为单位),在JIT之后:
For details (in ms), after JIT:
clone:68
arrayCopy:68
Arrays.copyOf:68
clone: 68
arrayCopy: 68
Arrays.copyOf: 68
测试代码:
public static void main(String[] args) throws InterruptedException,
IOException {
int sum = 0;
int[] warmup = new int[1];
warmup[0] = 1;
for (int i = 0; i < 15000; i++) { // triggers JIT
sum += copyClone(warmup);
sum += copyArrayCopy(warmup);
sum += copyCopyOf(warmup);
}
int count = 10_000_000;
int[] array = new int[count];
for (int i = 0; i < count; i++) {
array[i] = i;
}
// additional warmup for main
for (int i = 0; i < 10; i++) {
sum += copyArrayCopy(array);
}
System.gc();
// copyClone
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
sum += copyClone(array);
}
long end = System.nanoTime();
System.out.println("clone: " + (end - start) / 1000000);
System.gc();
// copyArrayCopy
start = System.nanoTime();
for (int i = 0; i < 10; i++) {
sum += copyArrayCopy(array);
}
end = System.nanoTime();
System.out.println("arrayCopy: " + (end - start) / 1000000);
System.gc();
// copyCopyOf
start = System.nanoTime();
for (int i = 0; i < 10; i++) {
sum += copyCopyOf(array);
}
end = System.nanoTime();
System.out.println("Arrays.copyOf: " + (end - start) / 1000000);
// sum
System.out.println(sum);
}
private static int copyClone(int[] array) {
int[] copy = array.clone();
return copy[copy.length - 1];
}
private static int copyArrayCopy(int[] array) {
int[] copy = new int[array.length];
System.arraycopy(array, 0, copy, 0, array.length);
return copy[copy.length - 1];
}
private static int copyCopyOf(int[] array) {
int[] copy = Arrays.copyOf(array, array.length);
return copy[copy.length - 1];
}
这篇关于.clone()或Arrays.copyOf()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文