在Java 6中向下转换有多昂贵? [英] How expensive is downcasting in Java 6?

查看:112
本文介绍了在Java 6中向下转换有多昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个方法接收类型 Collection 的参数,它需要使用 List code>类,当它使用该参数。是速度昂贵吗?

There is a method which receives an argument of type Collection and it needs to use some of the methods that are found in the List class when it does work with that argument. Is up-casting expensive in terms of speed?

List<Stuff> list = (List<Stuff>) collection;

我也想注意集合 object在此之后从不使用,只有 list ,并且这将被编译并在Oracle Java 1.6上运行。

I would also like to note that the collection object is never used after this, only the list, and that this will be compiled and run on Oracle Java 1.6.

推荐答案

严重的答案是由实际基准给出的。例如,我使用 jmh -targeting代码:

Serious answers are given by actual benchmarks. For example, I used this jmh-targeting code:

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

你需要解释,它是以下:没有任何区别

If you need interpretation, it is the following: there is no difference whatsoever.

这篇关于在Java 6中向下转换有多昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆