用了好久的泛型,突然听到有人说:泛型影响效率! 嘿,我这暴脾气! google 了一下,果然有很多人出来测试.最有气的是CSDN 上一个 楞种儿 测试出来 的结果 是:泛型比原始多一倍的时间.我一看测试代码,我就日.2个方法一起执行.后执行的运行时间肯定比先执行的快,应该是缓存的原因吧. 我改了改,弄了一个比较公平的 代码测试.结果我感觉好似 泛型在效率上稍微占点优势.另外看到一位大侠,用汇编语言测试,结果也差不多. 好了,让我们安心的用泛型吧! import java.util.ArrayList; public class Test { static long time = 0; //每次消耗时间 static long total=0; //总时间 static float average; //时间平均值 public static void main(String[] args) { for (int i = 0; i < 10; i++) { Generic();//泛型 } // for (int i = 0; i < 10; i++) { // NonGeneric();//原始类型 // } System.out.println("10次总时间: " + total + " ms");//10次消耗时间 System.out.println("10次平均值: " + average + " ms"); } //原始类型 public static void NonGeneric() { long start = System.currentTimeMillis();//开始时间 ArrayList no_list=new ArrayList(); for (int i = 0; i < 1000000; i++) { no_list.add(new Integer(i)); //添加 } for (int i = 0; i < 1000000; i++) { int j = ((Integer) no_list.get(i)).intValue();//取值 } long end = System.currentTimeMillis();//结束时间 time =(end - start); total +=time; average = total/10f; System.out.println("NonGeneric: " + time + " ms");//每次输出消耗时间 } //泛型 public static void Generic() { long start = System.currentTimeMillis();//开始时间 ArrayList<Integer> list = new ArrayList<Integer>(); for (int k = 0; k < 1000000; k++) { list.add(new Integer(k));//添加 } for (int n = 0; n < 1000000; n++) { int m = list.get(n).intValue();//取值 } long end = System.currentTimeMillis();//结束时间. time =(end - start); total +=time; average = total/10f; System.out.println("Generic: " + time + " ms");//每次输出消耗时间 } } 运行环境 硬件:cpu:AMD3k+ ; ram:金士顿ddr1 512*2 ; harddisk:希捷160g 7200转 8m 串 软件:os: xp ; myeclipse 6.5 ; jdk 1.6 比较如下: Generic: 375 ms Generic: 281 ms Generic: 297 ms Generic: 235 ms Generic: 203 ms Generic: 312 ms Generic: 219 ms Generic: 203 ms Generic: 312 ms Generic: 219 ms 10次总时间: 2656 ms 10次平均值: 265.6 ms | NonGeneric: 375 ms NonGeneric: 281 ms NonGeneric: 297 ms NonGeneric: 219 ms NonGeneric: 219 ms NonGeneric: 312 ms NonGeneric: 219 ms NonGeneric: 219 ms NonGeneric: 312 ms NonGeneric: 219 ms 10次总时间: 2672 ms 10次平均值: 267.2 ms
|
|