Array Copying: System.arraycopy vs Arrays.copyOf
1Concept
Copying arrays with manual for-loops is slow. `System.arraycopy()` is a native C/assembly method that performs a direct hardware memory block transfer (memmove). `Arrays.copyOf()` internally uses `System.arraycopy()`, while allocating a newly sized array.
2Architecture Diagram
[ Source Array ] [10, 20, 30, 40, 50]
|
System.arraycopy() (Native C memmove)
v
[ Target Array ] [ 0, 20, 30, 40, 0]3Code Example
Core Java
import java.util.Arrays;
public class ArrayCopyPerformanceDemo {
public static void main(String[] args) {
int[] source = {10, 20, 30, 40, 50};
int[] target = new int[5];
// Native memory block transfer: copy elements 1, 2, 3 into target at index 1
System.arraycopy(source, 1, target, 1, 3);
System.out.println("Target via System.arraycopy: " + Arrays.toString(target));
// Arrays.copyOf (allocates new array with custom length)
int[] expanded = Arrays.copyOf(source, 8);
System.out.println("Expanded via Arrays.copyOf: " + Arrays.toString(expanded));
}
}4Expected Output
Target via System.arraycopy: [0, 20, 30, 40, 0] Expanded via Arrays.copyOf: [10, 20, 30, 40, 50, 0, 0, 0]
5Key Takeaways
- ✓System.arraycopy is up to 5x faster than manual element-by-element loops.
- ✓Both methods perform shallow copies: object references are copied, NOT the objects themselves.
- ✓ArrayStoreException is thrown at runtime if target array type is incompatible with source.