Finding opportunities for System.arraycopy

20 Dec 2005

Fabio Insaccanebbia has come up with another fine rule for PMD - AvoidArrayLoops finds for/while loop array copies that can be replaced with a call to System.arraycopy. For example, this:

public class Foo {
 public void bar(int[] a, int[] b) {
  for (int i=0; i < 10; i++) {
   a[i] = b[i];
  }
 }
}

can be replaced with this:

public class Foo {
 public void bar(int[] a, int[] b) {
  System.arraycopy(b,0,a,0,a.length);
 }
}

Using System.arraycopy is more concise and is faster, too, since it's usually implemented with native code.

Running this rule on the JDK found some straightforward replacement candidates, such as this snippet from MessageFormat.setFormats:

for (int i = 0; i < runsToCopy; i++) {
 formats[i] = newFormats[i];
}

You'll find this rule checked in to the PMD CVS repository in the optimizations ruleset; and a PMD 3.5 release is not far away. Thanks again to Fabio for his excellent contributions!