Copying Arrays in Java 6
Performance and Alternatives
I can actually use the
clone method to copy a source array into a target array, so technically
copyOf isn't necessary. However, my hastily written performance tests demonstrate that
clone is fairly slow. They also demonstrate that
copyOf is a mite slower than
arraycopy. It's probably not enough for me to worry about, so I'll use the new
copyOf method. As always, I'll profile if necessary.
Is the new set of
copyOf methods an essential addition to Java? Absolutely not. It could easily be looked at as syntactical sugar. There's no reason I couldn't continue to use
arraycopy. However, it's in line with simplifying efforts to code Java applications, something that Sun promoted heavily with the introduction of Java 5.
About the Author
Jeff Langr is a veteran software developer with a score and more years
of experience. He's authored two books and dozens of published articles
on software development, including Agile Java: Crafting Code
With Test-Driven Development (Prentice Hall) in 2005. You can find out more
about Jeff at his site, http://langrsoft.com, or you can contact him directly at email@example.com.
Page 2 of 2