Friday, March 11, 2005

How to copy arrays fast

Introduction

What is the fastest way of copying an array from array a to array b?

Program

class ArrayCopy {
    public static void main(String[] args) {
        // initialize arrays
        int[] a = {1, 2, 3};
        int[] b = new int[a.length];

        System.arraycopy(a, 0, b, 0, a.length); // fastest
        for (int i = 0; i < a.length; i++) b[i] = a[i]; // 4 times slower
        b = (int[]) a.clone(); // 7 times slower
    }
}

Conclusion

Do not use method clone() if there is an alternative. Use method System.arraycopy() when copying arrays.

Resources

No comments: