Java foreach 效率 [英] Java foreach efficiency

查看:13
本文介绍了Java foreach 效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

Map<String, String> myMap = ...;

for(String key : myMap.keySet()) {
   System.out.println(key);
   System.out.println(myMap.get(key)); 
}

那么 myMap.keySet()foreach 循环 中被调用一次了吗?我认为是的,但希望得到您的意见.

So is myMap.keySet() called once in the foreach loop? I think it is, but want your opinion.

我想知道以这种方式使用 foreach (myMap.keySet()) 是否对性能有影响或等同于:

I would like to know if using foreach in this way (myMap.keySet()) has a performance impact or it is equivalent to this:

Set<String> keySet = myMap.keySet();
for (String key : keySet) {
   ...
}

推荐答案

如果你想绝对确定,那就两种方式编译,反编译比较.我使用以下来源进行了此操作:

If you want to be absolutely certain, then compile it both ways and decompile it and compare. I did this with the following source:

public void test() {
  Map<String, String> myMap = new HashMap<String, String>();

  for (String key : myMap.keySet()) {
    System.out.println(key);
    System.out.println(myMap.get(key));
  }

  Set<String> keySet = myMap.keySet();
  for (String key : keySet) {
    System.out.println(key);
    System.out.println(myMap.get(key));
  }
}

当我用 Jad 反编译类文件时,我得到:

and when I decompiled the class file with Jad, I get:

public void test()
{
    Map myMap = new HashMap();
    String key;
    for(Iterator iterator = myMap.keySet().iterator(); iterator.hasNext(); System.out.println((String)myMap.get(key)))
    {
        key = (String)iterator.next();
        System.out.println(key);
    }

    Set keySet = myMap.keySet();
    String key;
    for(Iterator iterator1 = keySet.iterator(); iterator1.hasNext(); System.out.println((String)myMap.get(key)))
    {
        key = (String)iterator1.next();
        System.out.println(key);
    }
}

这就是你的答案.使用任一 for 循环形式调用一次.

So there's your answer. It is called once with either for-loop form.

这篇关于Java foreach 效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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