速记循环是否缓存可迭代对象的引用? [英] Does shorthand for loop cache the iterable's reference?

查看:86
本文介绍了速记循环是否缓存可迭代对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会试图过高效率,但是我一直想知道以下两个代码示例中的哪一个可以更快地执行.

I am likely trying to be over-efficient, but I have been wondering which of the following two code samples would execute more quickly.

假定您对包含ArrayList Strings的对象的引用,并且要遍历该列表.以下哪一项效率更高(即使只是略微提高效率)?

Assume that you have a reference to an object which contains an ArrayList of Strings and you want to iterate through that list. Which of the following is more efficient (even if only marginally so)?

for(String s : foo.getStringList())
    System.out.println(s);

ArrayList<String> stringArray = foo.getStringList();
for(String s : stringArray)
    System.out.println(s);

如您所见,第二个循环初始化对列表的引用,而不是像第一个示例那样每次迭代都调用它.除非这个概念是完全错误的,并且它们都以相同的方式起作用,因为Java的内部工作方式会创建它们自己的引用变量.

As you can see, the second loop initializes a reference to the list instead of calling for it every iteration, as it seems the first sample does. Unless this notion is completely incorrect and they both function the same way because the inner workings of Java create their own reference variable.

所以我的问题是,是什么?

So my question is, which is it?

推荐答案

没有什么区别,因为两个循环最终都只会在循环开始时获得并维护对表达式的Iterator的引用.这是 Java语言的摘录规格:

There's no difference, because both loops only end up getting and maintaining a reference to an Iterator for the expression at the start of the loop. Here's an excerpt from the Java Language Specification:

增强的for语句等效于以下形式的基本for语句:

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

这篇关于速记循环是否缓存可迭代对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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