Java的for-each是否为每次迭代都调用嵌入式方法(返回集合)? [英] Does Java's for-each call an embedded method (that returns the collection) for every iteration?

查看:85
本文介绍了Java的for-each是否为每次迭代都调用嵌入式方法(返回集合)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有方法调用MyClass.returnArray(),并且我使用for-each构造(也称为"enhanced for"循环)遍历数组:

If there is a method call MyClass.returnArray() and I iterate over the array using the for-each construct (also called the "enhanced for" loop):

for (ArrayElement e : MyClass.returnArray()) {
   //do something
}

然后每次迭代都会调用returnArray()方法吗?

will then the returnArray() method be called for every iteration?

推荐答案

否,不会.第一次调用的结果将存储在编译后的代码中的一个临时变量中.

No, it won't. The result of the first call will be stored in the compiled code in a temporary variable.

来自有效的Java 2nd.编.,第46项:

请注意,使用此功能不会降低性能 for-each循环,即使对于数组也是如此.实际上,它可能会提供一点性能优势 在某些情况下,通过普通的for循环,因为它计算了 数组索引仅一次.

Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.

这篇关于Java的for-each是否为每次迭代都调用嵌入式方法(返回集合)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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