<分区>
有一个方法接收类型为 Collection
的参数,它需要使用在 List
类中找到的一些方法争论。向上转换在速度方面是否昂贵?
List<Stuff> list = (List<Stuff>) collection;
我还想指出,此后不再使用collection
对象,仅使用list
,并且将在Oracle Java 1.6 上编译和运行。
<分区>
有一个方法接收类型为 Collection
的参数,它需要使用在 List
类中找到的一些方法争论。向上转换在速度方面是否昂贵?
List<Stuff> list = (List<Stuff>) collection;
我还想指出,此后不再使用collection
对象,仅使用list
,并且将在Oracle Java 1.6 上编译和运行。
最佳答案
严肃的答案由实际基准给出。例如,我使用了这个 jmh
定位代码:
public class Benchmark1
{
static final List<Integer>[] lists = new List[10000]; static {
for (int i = 0; i < lists.length; i++) {
lists[i] = new ArrayList<Integer>(1);
lists[i].add(1);
}
}
static final Collection<Integer>[] colls = new Collection[lists.length]; static {
for (int i = 0; i < colls.length; i++) colls[i] = lists[i];
}
@GenerateMicroBenchmark
public long testNoDowncast() {
long sum = (long)Math.random()*10;
for (int i = 0; i < lists.length; i++) sum += lists[i].get(0);
return sum;
}
@GenerateMicroBenchmark
public long testDowncast() {
long sum = (long)Math.random()*10;
for (int i = 0; i < colls.length; i++) sum += ((List<Integer>)colls[i]).get(0);
return sum;
}
}
jmh
提供了以下结果:
Benchmark Mode Thr Cnt Sec Mean Mean error Units
testDowncast thrpt 1 5 5 18.545 0.019 ops/msec
testNoDowncast thrpt 1 5 5 19.102 0.655 ops/msec
如果需要解释,那就是:没有任何区别。
关于java - Java 6 中的向下转型有多昂贵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764092/