Title: Does a method call in in a for loop declaration affect performance?
Tags: java
Question: For example is this
for (String s : getStrings()) {
// do something
less efficient than this?
ArrayList<String&gt; strings = getStrings();
for (String s : strings) {
// do something
Would getStrings() get called every time, thus affecting performance?
Comment: I think the compiler takes care of that, so both are as efficient.

Comment: It actually makes no difference. The enhanced for loop is compiled into the same code as with using an iterator, so the method will be called only once. See the linked question.

Comment: @Tunaki, thanks for the link



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:06/29/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java>', 'Title': 'Does a method call in in a for loop declaration affect performance?', 'ViewCount': 26, 'id': 38105167, 'user_AboutMe': '<p>while(true){beNiceToPeople()}</p>\n', 'user_AccountId': 4081547.0, 'user_DisplayName': 'secondbreakfast', 'user_Reputation': 3922.0, 'user_Views': 434.0, 'user_id': 3351924.0}}