论坛首页 Java企业应用论坛

深入理解java的clone

浏览 30269 次
该帖已经被评为良好帖
作者 正文
   发表时间:2010-08-19   最后修改:2010-08-19
to 楼主:

性能

不可否认,JVM越来越快了。
但是系统默认的native实现还是挺快的。
clone一个有100个元素的int数组,用系统默认的clone比静态copy方法快2倍左右。

------------------------------------------------------------------

针对这个我做了下测试。
iint fortimes = 1000 * 100;
        int n = 10000;
        int[] ints = new int[n];
        for (int i = 0; i < n; i++) {
            ints[i] = i;
        }

        long start = System.currentTimeMillis();
        for (int i = 0; i < fortimes; i++) {
            ints.clone();
        }
        System.out.println("clone cost: " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        int[] intsCopy = new int[n];
        for (int i = 0; i < fortimes; i++) {
            System.arraycopy(ints, 0, intsCopy, 0, ints.length);
        }
        System.out.println("copy cost: " + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        int[] intsfor = new int[n];
        for (int i = 0; i < fortimes; i++) {
            int length = ints.length;
            for (int j = 0; j < length; j++) {
                intsfor[j] = ints[j];
            }
        }
        System.out.println("for copy cost: " + (System.currentTimeMillis() - start));


发现性能没你说的那么好,发现还不如我循环copy来得快。
clone cost: 2698 ms
copy cost: 480 ms
for copy cost: 496 ms


针对String对象的我也做了类似测试,发现效果也没系统的system.arraycopy来的好
clone cost: 2636
copy cost: 523
for copy cost: 2882


不知道LZ的2倍性能提升是咋来的,做了特殊优化?
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics