在Java 6中,向下转换的成本有多高?
有一个方法接收Collection
类型的参数,它需要使用List
类中的一些方法,当它与该参数一起使用时。 在速度方面上升昂贵吗?
List list = (List) collection;
我还要注意,在此之后永远不会使用collection
对象,只有list
,并且这将在Oracle Java 1.6上编译和运行。
实际基准给出了严肃的答案。 例如,我使用了这个jmh
-targeting代码:
public class Benchmark1 { static final List[] lists = new List[10000]; static { for (int i = 0; i < lists.length; i++) { lists[i] = new ArrayList (1); lists[i].add(1); } } static final Collection [] 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 )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
如果您需要解释,则如下: 没有任何区别 。