CSDN博客

img yoti

JDK 1.5中泛型(Generics type)的性能测试再测试

发表于2004/10/31 14:36:00  698人阅读

分类: JAVA

  我看了http://dev.csdn.net/develop/article/41/41137.shtm后,再自己添加了一些代码,然后重新测试。结果我发现根本说不上速度变慢了,而只是在一个很小的范围内波动。

import java.util.ArrayList;
import java.util.List;

/**
 * @author yoti
 * 在JDK 1.5下
 */

public class PerformanceTest {

    /** Creates a new instance of PerformanceTest */

    public PerformanceTest() {}

    public static void main(String[] args) {
        long[] beforeAdd = new long[2];
        long[] afterAdd = new long[2];
        long[] beforeGet = new long[2];    
        long[] afterGet = new long[2];
        double[] sumAdd = new double[2];
        double[] sumGet = new double[2];
        int oneOrTwo = 0;

        System.out.println(
                "java.version=" + System.getProperty("java.version"));
        for (int k = 0; k < 100; k++) {
            if ((k % 2) == 0) {
                List list = new ArrayList();
                beforeAdd[0] = System.currentTimeMillis();
                int end = 100000;
                for (int i = 0; i < end; i++) {
                    list.add(new Integer(i));
                }
                afterAdd[0] = System.currentTimeMillis();

                beforeGet[0] = System.currentTimeMillis();
                for (int j = 0; j < end; j++) {
                    Integer integer = (Integer) list.get(j);
                }
                afterGet[0] = System.currentTimeMillis();
            } else {
                List<Integer> list = new ArrayList<Integer>();
                beforeAdd[1] = System.currentTimeMillis();
                int end = 100000;
                for (int i = 0; i < end; i++) {
                    list.add(new Integer(i));
                }
                afterAdd[1] = System.currentTimeMillis();

                beforeGet[1] = System.currentTimeMillis();
                for (int j = 0; j < end; j++) {
                    Integer integer = (Integer) list.get(j);
                }

                afterGet[1] = System.currentTimeMillis();
            }
            oneOrTwo = k % 2;
            double addTime = (afterAdd[oneOrTwo] - beforeAdd[oneOrTwo]) / 1000.0d;
            double getTime = (afterGet[oneOrTwo] - beforeGet[oneOrTwo]) / 1000.0d;
            sumAdd[oneOrTwo] += addTime;
            sumGet[oneOrTwo] += getTime;
        }
        System.out.println("不使用generics时Add总耗时:" + sumAdd[0]);
        System.out.println("使用generics后Add总耗时:" + sumAdd[1]);
        System.out.println("不使用generics时Get总耗时:" + sumGet[0]);
        System.out.println("使用generics后Get总耗时:" + sumGet[1]);
    }
}


java.version=1.5.0
不使用generics时Add总耗时:12.318
使用generics后Add总耗时:12.658
不使用generics时Get总耗时:0.40100000000000025
使用generics后Get总耗时:0.4200000000000002

//另一次测试
java.version=1.5.0
不使用generics时Add总耗时:13.358999999999993
使用generics后Add总耗时:13.127999999999998
不使用generics时Get总耗时:0.5120000000000002
使用generics后Get总耗时:0.3900000000000001

阅读全文
0 0

相关文章推荐

img
取 消
img