Home  >  Article  >  Java  >  Example of efficiency comparison analysis of Java two-dimensional array copy

Example of efficiency comparison analysis of Java two-dimensional array copy

WBOY
WBOYforward
2023-04-25 15:04:08865browse

1.for loop

public static void show1(int[][] array){
        for(int i = 0;i < array.length;i++){
            for(int j = 0;j < array[i].length;j++){
                System.out.print(array[i][j]+" ");
            }
            System.out.println();
        }
    }

2.clone()

/**
 * 使用数组本身的 clone() 方法
 *
 * @param sourceArr 源数组
 * @param destArr   目标数组
 */
public static void copy3(int[][] sourceArr, int[][] destArr) {
    for (int i = 0; i < sourceArr.length; i++) {
        destArr[i] = sourceArr[i].clone();
    }
}

3.Arrays.arraycopy

int[][] array = {{1,2,3},{4,5,6}};
        int[][] array2 = new int[2][3];
        for(int i = 0;i < array.length;i++){
            System.arraycopy(array[i], 0, array2[i],
                    0, array[i].length);

4. Speed ​​comparison

arraycopy source code, this method copies the fastest and has no return value.

@HotSpotIntrinsicCandidate
public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

The above is the detailed content of Example of efficiency comparison analysis of Java two-dimensional array copy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete