In an effort to reduce mutability, should we rather use
public void setValues(String[] newVals) {
this.vals = ( newVals == null ? null : newVals.clone() );
}
or
public void setValues(String[] newVals) {
this.vals = ( newVals == null ? null : Arrays.copyOf(newVals, newVals.length) );
}
I written a simple program to check the difference.
And it outputs
So if you see in both case
String[]
is immutable and performance is almost same thought Arrays.copyOf() is slightly faster on my machine.Update
I changed program to create large array[100 strings] rather than small array.
And moved
copy of
method beforeclone
method. With below results.Which are again more of same.
Please do not ask me to run the test again as it takes a while
:(Update 2
For String array
1000000
and for number of iterations10000
copy of
takes more time thanclone
Update using jmh
Using jmh, I get similar results, except that
clone
seems to be marginally better.Original post
I ran a quick test for performance:
clone
,System.arrayCopy
andArrays.copyOf
have very similar performance (jdk 1.7.06, server vm).For details (in ms), after JIT:
Test code:
In terms of mutability, they will provide exactly the same - shallow copy of data.
Please also consider the security of using "clone()". A class of well-known attacks use classes that override objects' "clone()" methods with malicious code. For example, CVE-2012-0507 (the "Flashback" attack on Mac OS) was addressed by basically replacing a ".clone()" call with a ".copyOf" call.
Additional discussion on the obsolete-ness of "clone()" can be found on StackOverflow here: object cloning with out implementing cloneable interface