System.arraycopy 为什么比手写循环快?它和 Arrays.copyOf、clone 有什么区别?这篇先看语义(重叠、类型检查、异常),再用 JIT 开关把「JVM 特殊优化」量出来(不看 HotSpot 源码,只用实测;JIT 本身见前面一篇)。
System.arraycopy(x, 0, x, 1, 5)(同一数组、区间重叠)→ [1, 1, 2, 3, 4, 5](像先复制到临时数组再写回)
自己写的从前往后的循环 y[i+1] = y[i] → [1, 1, 1, 1, 1, 1](重叠时被覆盖,整行都变成 1)
从后往前的循环 → [1, 1, 2, 3, 4, 5]
Object[]{"a","b",3,"d"} 复制到 String[]:抛 ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.String;已经复制进去的:[a, b, null, null](失败前的元素已经被复制)
目标放不下 → ArrayIndexOutOfBoundsException: arraycopy: last destination index 6 out of bounds for int[3];目标数组 = [0, 0, 0](越界检查在复制之前,没有部分复制)
int[] → long[] → ArrayStoreException: arraycopy: type mismatch: can not copy int[] into long[]
源是 null → NullPointerException
复制 0 个元素、起点等于长度:System.arraycopy(new int[3], 3, new int[3], 3, 0) 不抛异常System.arraycopy 0.069 ns/元素(复制 1048576 个 int,后 4 轮取最好) 手写 for 循环 0.177 ns/元素(复制 1048576 个 int,后 4 轮取最好) Arrays.copyOf 0.077 ns/元素(复制 1048576 个 int,后 4 轮取最好) src.clone() 0.072 ns/元素(复制 1048576 个 int,后 4 轮取最好) Arrays.copyOfRange(整段) 0.071 ns/元素(复制 1048576 个 int,后 4 轮取最好)
[默认(有 JIT)] 最后一轮:System.arraycopy 0.079 ns/元素,手写循环 0.173 ns/元素 [-Xint(纯解释器)] 最后一轮:System.arraycopy 0.157 ns/元素,手写循环 7.554 ns/元素