今天公司有个同事,说泛型影响性能,不用泛型的话,性能高七倍,对此,我深表怀疑,于是自己动手,测试了一下,测试并不严谨,大家见谅
测试代码如下,为了防止java虚拟机对foreach或者对迭代器有特殊优化,所以采用最原始的for循环,同时为了防止基本类型拆装箱影响测试结果,采用了我项目里一个很简单的bean。
这个是有泛型的类:
package com.test;
import java.util.ArrayList;
import java.util.List;
import com.mobcent.aca.domain.DeveloperApp;
public class GenericTest implements Runnable {
Thread thread = new Thread(this);
public void start() {
thread.start();
}
public void run() {
// TODO Auto-generated method stub
double total = 0;
for (int i = 0; i < 10000; i++)
total = total + Generic();
System.out.println("Generic: " + total + " ms");
}
public long Generic() {
long start = System.currentTimeMillis();
List<DeveloperApp> v = new ArrayList<DeveloperApp>();
for (int i = 0; i < 10240; i++) {
v.add(new DeveloperApp());
}
for (int i = 0; i < 10240; i++) {
DeveloperApp j = v.get(i);
}
long end = System.currentTimeMillis();
return end - start;
}
}
这个是没有泛型的类package com.test;
import java.util.ArrayList;
import java.util.List;
import com.mobcent.aca.domain.DeveloperApp;
public class NonGenericTest implements Runnable {
Thread thread = new Thread(this);
public void start() {
thread.start();
}
public void run() {
// TODO Auto-generated method stub
double total = 0;
for (int i = 0; i < 10000; i++)
total = total + NonGeneric();
System.out.println("NonGeneric: " + total + " ms");
}
public long NonGeneric() {
long start = System.currentTimeMillis();
List v = new ArrayList();
for (int i = 0; i < 10240; i++) {
v.add(new DeveloperApp());
}
for (int i = 0; i < 10240; i++) {
DeveloperApp j = (DeveloperApp) v.get(i);
}
long end = System.currentTimeMillis();
return end - start;
}
}
以下是测试结果
有泛型 | 无泛型 |
4595.0 ms | 4664.0 ms |
4539.0 ms | 4567.0 ms |
4570.0 ms | 4513.0 ms |
然后还测试了以下同时两个线程的情况,进行对比:
无泛型 | 无泛型 |
9233.0 ms | 9372.0 ms |
9237.0 ms | 9420.0 ms |
9338.0 ms | 9428.0 ms |
我的测试不是很严谨,随手做的小测试。
至于原因,我想大家应该大部分都知道。泛型仅仅是java的语法糖,它不会影响java虚拟机生成的汇编代码,在编译阶段,虚拟机就会把泛型的类型擦除,还原成没有泛型的代码,所以网上说java用泛型比不用泛型速度慢7倍纯属无稽之谈,顶多编译速度稍微慢一些,执行速度是完全没有什么区别的.