打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
泛型的效率和原始类的效率比较
用了好久的泛型,突然听到有人说:泛型影响效率! 嘿,我这暴脾气! 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   msNonGeneric:   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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java遍历文件夹的2种方法_王炜华的空间
正确使用arraylist和linkedlist—性能的改进
Java中ArrayList和LinkedList区别
Java性能优化之编程技巧总结
Java并发编程总结4
Java提高篇(三二)-----List总结
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服