我编写了一个简单的程序来检查差异。
public static void main(String[] args) throws IOException, InterruptedException,
PrinterException
{
String[] str = {"a","b","c"};
String[] strings = str.clone();
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));
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));
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);
}
在 clone
方法之前移动了 copy of
方法。以下是结果。
Time Required for Copy of: 415095
Time Required for Clone: 428501
这些都是同样的内容。请不要让我再次运行测试,因为需要一段时间
:(
更新2
对于字符串数组1000000
和迭代次数10000
Time Required for Copy of: 32825
Time Required for Clone: 30138
copy of
比 clone
花费更多的时间。
vals
是Object vals
,否则以上内容无法编译。否则,这些方法是可比较的。clone
是一个更简单的调用(除了丑陋的向下转换)。 - Marko TopolnikSystem.arrayCopy()
怎么样?(这比你的两个选项更快) - assyliasclone
应该至少和它一样快,它会对实例数据进行逐字节的复制。 - Marko Topolnik