对数组arraycopy、clone和普通的循环赋值的性能分析

下面是测试的代码:
public class ArrayCopyPerformanceTest {

	public static class Person {
        public String name;
    }
    public static void main(String[] args) {
        int arraySize = 1000;
        int testTimes = 100000;
 
        Person[] ps1 = genPersons(arraySize);
 
        long t1 = System.currentTimeMillis();
        Person[] ps2 = new Person[arraySize];
        for (int i = 0; i < testTimes; i++) {
            System.arraycopy(ps1, 0, ps2, 0, arraySize);
        }
        long t2 = System.currentTimeMillis();
        System.out.println("time used by System.arraycopy: " + (t2 - t1) + "ms");

        long t = System.currentTimeMillis();
        Person[] ps = new Person[arraySize];
        for (int i = 0; i < testTimes; i++) {
        	ps2 = ps1.clone();
        }
        long tt = System.currentTimeMillis();
        System.out.println("time used by clone: " + (tt - t) + "ms");
 
        t1 = System.currentTimeMillis();
        ps2 = new Person[arraySize];
        for (int i = 0; i < testTimes; i++) {
            for (int j = 0; j < arraySize; j++) {
                ps2[j] = ps1[j];
            }
        }
        t2 = System.currentTimeMillis();
        System.out.println("time used by manual loop: " + (t2 - t1) + "ms");
    }
 
    public static Person[] genPersons(int arraySize) {
        Person[] ps = new Person[arraySize];
        for (int i = 0; i < arraySize; i++) {
            Person p = new Person();
            p.name = "james" + i;
            ps[i] = p;
        }
 
        return ps;
    }

}

执行的结果:

time used by System.arraycopy: 116ms
time used by clone: 370ms
time used by manual loop: 641ms

从结果来看性能还是会有不小的差距的,clone虽然在性能上较之普通循环赋值有所提升,但是,不够灵活,不能指定赋值的元素,而且,java内置的集合类型,eg,ArrayList,内部的add()和remove()方法的内部实现都是用arraycopy的。所以,综合来说,对于批量数据的赋值推荐用arraycopy。

你可能感兴趣的:(对数组arraycopy、clone和普通的循环赋值的性能分析)