Use System.arraycopy() Instead of Loop

ID

java.loop_arraycopy

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

best-practice, efficiency

Description

Reports for-loops that copy array elements one by one using indexed assignment (e.g., dest[i] = src[i]).

Rationale

Manually copying arrays element-by-element in a loop is significantly slower than using System.arraycopy(), which is implemented as a native memory operation. For large arrays, the performance difference can be substantial.

// Bad - manual element-by-element copy
for (int i = 0; i < source.length; i++) {
    dest[i] = source[i];
}

Remediation

Use System.arraycopy() or Arrays.copyOf() for array copying.

// Good - native array copy
System.arraycopy(source, 0, dest, 0, source.length);

// Also good
int[] dest = Arrays.copyOf(source, source.length);