Does Java's for-each call an embedded method (that returns the collection) for every iteration?

前端 未结 4 1139
借酒劲吻你
借酒劲吻你 2021-02-03 20:41

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):

f         


        
4条回答
  •  走了就别回头了
    2021-02-03 21:20

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

    From Effective Java 2nd. Ed., Item 46:

    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.

提交回复
热议问题