How expensive is downcasting in Java 6? [closed]

爷,独闯天下 提交于 2019-12-18 07:08:59

问题


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;

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.


回答1:


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;
  }
}

And jmh provided the following results:

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.



来源:https://stackoverflow.com/questions/17764092/how-expensive-is-downcasting-in-java-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!