跳到主要内容

数组拷贝性能优化

方式一: System.arraycopy() (性能最高)

  • 基本数组复制
  • 数组部分复制
  • 数组扩容与合并
  • 数组元素移动
  • 多维数组复制
public static native void arraycopy(
Object src, // 源数组
int srcPos, // 源数组起始位置(0表示数组第一个元素)
Object dest, // 目标数组
int destPos, // 目标数组起始位置(0表示数组第一个元素)
int length // 要复制的元素数量,从源数组srcPos的索引开始
)

一个基本的数组复制代码案例:

// 复制整个数组
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
System.arraycopy(source, 0, destination, 0, source.length);
// destination: [1, 2, 3, 4, 5]

方式二: Arrays.copyOf()

方式三:for循环(性能最差)

方式四: clone()