我写了一个简单的程序来检查差异。
public static void main(String[] args) throws IOException, InterruptedException,
PrinterException
{
//Verify array remains immutable.
String[] str = {"a","b","c"};
String[] strings = str.clone();
//change returned array
strings[2]= "d";
System.out.println(Arrays.toString(str));
System.out.println(Arrays.toString(strings));
String[] stringsCopy = Arrays.copyOf(str, str.length);
stringsCopy[2]= "d";
System.out.println(Arrays.toString(str));
System.out.println(Arrays.toString(stringsCopy));
//peformance
long before = System.currentTimeMillis();
for(int i=0;i<Integer.MAX_VALUE;i++)
{
str.clone();
}
System.out.println("Time Required for Clone: "+ (System.currentTimeMillis()-before));
//peformance
long beforeCopy = System.currentTimeMillis();
for(int i=0;i<Integer.MAX_VALUE;i++)
{
Arrays.copyOf(str, str.length);
}
System.out.println("Time Required for Copy of: "+ (System.currentTimeMillis()-beforeCopy));
}
它输出
[a, b, c]
[a, b, d]
[a, b, c]
[a, b, d]
Time Required for Clone: 26288
Time Required for Copy of: 25413
因此,如果您看到这两种情况String[]
都是不可变的并且性能几乎相同,那么认为 Arrays.copyOf() 在我的机器上稍快一些。
更新
我更改了程序以创建大数组 [100 个字符串] 而不是小数组。
String[] str = new String[100];
for(int i= 0; i<str.length;i++)
{
str[i]= Integer.toString(i);
}
并在copy of
方法之前移动clone
方法。结果如下。
Time Required for Copy of: 415095
Time Required for Clone: 428501
这又是相同的。Please do not ask me to run the test again as it takes a while
:(
更新 2
对于字符串数组1000000
和迭代次数10000
Time Required for Copy of: 32825
Time Required for Clone: 30138
copy of
花费的时间比clone