array clone() vs Arrays.copyOf()

David Holmes David.Holmes at oracle.com
Wed Apr 27 00:34:52 UTC 2011


Hi Stuart,

Actually my comments more a response to Remi's assertion that clone 
should have been used instead, without giving any technical rationale as 
to why clone would be better, and so much better that it warranted Lance 
changing the code.

Personally I think we should be steering people to Arrays.copyOf for all 
their array copying needs. clone() is effectively legacy code. It may 
have a small performance benefit though ultimately both methods are 
intrinisified by the same C2 code so I don't believe the gain would be 
much, and likely only with smaller arrays.

BTW I think Lance received communication from others over the use of 
copyOf versus clone, I never made any additional comments on the 
relative merits.

Cheers,
David

Stuart Marks said the following on 04/27/11 01:20:
> Hi David,
> 
> I have a general code style question about this. This arose in the 
> review of Lance's webrevs for 7038565 [1] but I'm starting a new thread 
> since I don't want further discussion to drag out that review.
> 
> In that review, Lance initially used Arrays.copyOf() to do defensive 
> copying of an array. Rémi suggested calling clone() instead, and Lance 
> changed it, but it looks like you (David) convinced him to change it 
> back to use Arrays.copyOf().
> 
> (Quotes from the emails are below, but the attribution is hard to follow.)
> 
> What's the rationale for using Arrays.copyOf() in this case? To me, 
> clone() is the clearest and most concise way of making the copy. 
> Arrays.copyOf() is slightly more verbose and the reader has to do a tiny 
> bit of analysis to determine that the length isn't being changed, since 
> the value passed is the current length. Is there some other reason I'm 
> not aware of that Arrays.copyOf() should be preferred?
> 
> I guess, one point is that it's hard to find the javadoc for the array 
> clone() call. :-)
> 
> I guess I'm mainly aiming this at David since he seemed to be the 
> strongest advocate for the use of Arrays.copyOf(), but I'd welcome 
> opinions from others as well.
> 
> s'marks
> 
> [1] 
> http://mail.openjdk.java.net/pipermail/core-libs-dev/2011-April/006694.html
> 
> On 4/25/11 9:28 AM, Lance Andersen - Oracle wrote:
>> On Apr 23, 2011, at 6:11 AM, David Holmes wrote:
>>
>>> >  Rémi Forax said the following on 04/23/11 04:22:
>>>> >>  On 04/22/2011 06:51 PM, Lance Andersen - Oracle wrote:
>>>>>> >>>>
>>>>>> >>>>  You should use clone() instead of Arrays.copyOf.
>>>>> >>>
>>>>> >>>  Can you explain why  you have a preference for clone() in this 
>>>>> case?
>>>> >>  It does the job :)
>>>> >>  Arrays.copyOf() allows to resize the array.
>>> >
>>> >  So? That's not a reason to not use Arrays.copyOf. Look at copyOf 
>>> as the new improved version of clone.
>>> >



More information about the core-libs-dev mailing list