Array .clone() or System.arraycopy()?

I was doing some work this morning with passwords stored as char arrays when I reverted to my C upbringing and wrote the following:

final char[] passwordCopy = new char[password.length];
System.arraycopy(password, 0, passwordCopy, 0, password.length);

I stopped myself and said: Hey! Why am I doing that when arrays have a convenient .clone() method on them?!? I rewrote the code to be the following:

final char[] passwordCopy = (char[])password.clone();

The QA side of me really likes the latter approach as it has a much lower risk associated with it (i.e. there are fewer ways to make a mistake), but the performance side said Whoa! Let’s take a look at performance first!

I was going to write up a quick test but the lazy side of me went to Google first. This page has a nice test and performance numbers. The shocking result is System.arraycopy() vs. a for loop. Based on a few JVM’s I tried (all on win32) I get the following normalized results:

.clone():  2.26
System.arraycopy():  1.27
for-loop():  1.00


  1. As a matter of fact, that’s the first thing that came into my head when I saw the results.
    Given the performance improvements that appear in 1.5, I wonder if the tides will turn on this one too. At this point I’m too lazy to download a 1.5 to try *grin*.

  2. I’ve just run some tests on 5.0:
    1MB arrays, copied 500 times:
    for: 13.9
    clone: 11.9
    arraycopy: 11.8
    100KB arrays, copied 5000 times:
    for: 3.8
    clone: 1.5
    arraycopy: 1.5
    10KB arrays, copyied 50000 times:
    for: 3.8
    clone: 1.3
    arraycopy: 1.3
    100B arrays, copied 5000000 times:
    clone: 4.1
    for: 3.7
    arraycopy: 1.5
    It seems arraycopy wins out every time, while for loops are faster for everything except small arrays.
    Of course, clone() is no good for copying just part of an array anyway, so it loses out to arraycopy() in most situations by default anyway.
    On another note: Why is arraycopy() in System? I didn’t realise it existed until today as I was always looking in Array.

  3. Thanks for the 1.5 update. System.arraycopy() appears to be the best choice regardless but is unfortunately one of the more error-prone techniques.
    As for why it’s not in Arrays: that’s historical. There was no java.util.Arrays before 1.2.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s