Java › Arrays & Multidimensional Arrays
How would you efficiently copy, resize, or merge large arrays in Java, and what are the performance trade-offs between System.arraycopy(), Arrays.copyOf(), and manual loops?
AdvancedAnswer
System.arraycopy() is a native method performing highly optimized bulk memory copying (often using intrinsic CPU instructions), generally the fastest option for copying array ranges; Arrays.copyOf() internally calls System.arraycopy() but adds the convenience of allocating the destination array for you, at the cost of one extra layer of indirection; a manual element-by-element loop is almost always slower than either since it can't benefit from the same low-level bulk-copy optimizations, and should generally be avoided for simple copy operations in favor of the built-in methods.
int[] source = {1, 2, 3, 4, 5};
// Fastest for a pre-allocated destination
int[] dest = new int[5];
System.arraycopy(source, 0, dest, 0, source.length);
// Convenient, internally uses System.arraycopy
int[] resized = Arrays.copyOf(source, 10); // pads with zeros
// Merging two arrays efficiently
int[] merged = new int[source.length + dest.length];
System.arraycopy(source, 0, merged, 0, source.length);
System.arraycopy(dest, 0, merged, source.length, dest.length);Real-world example A high-throughput data pipeline processing large numeric arrays uses System.arraycopy() directly for merging and resizing buffers, having profiled that this measurably outperforms a naive manual copy loop at the scale the pipeline operates, since arraycopy benefits from JIT intrinsics mapping directly to optimized native memory operations.