Reputation: 60204
Well, it is stated in Performance Tips that:
So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.
But looking at ioshed 2013 application, which is considered to be an example for most developers, in ScheduleUpdaterService.java
in particular I can see the following:
void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (IOException e) {
// TODO: do something useful here, like revert the changes locally in the
// content provider to maintain client/server sync
LOGE(TAG, "Error processing schedule update", e);
}
}
Please notice there is an enhanced for loop iteration through scheduleUpdates
, while it is suggested to avoid such type of iteration for ArrayList
.
Is that because this part of the application is not considered to be critical from performance standpoint or am I not understanding something? Thanks a lot.
Upvotes: 0
Views: 1327
Reputation: 691913
Yes. Readability and maintainability is much more important than performance in 99.999% of the cases. The performance tip says: "you should use the enhanced for loop by default".
So, unless you have a performance problem, and you've proven that transforming the foreach loop to a counted loop solves this performance problem, or at least significantly improves the situation, you should favor readability and maintainability, and thus the foreach loop.
Upvotes: 2
Reputation: 41281
Yes, there is a small performance loss via the iterator. A regular for loop that uses this iterator will also encounter such losses, while iterating manually would be slightly faster. However this is extremely small(on the order of nanoseconds as seen here), and is negligible.
Optimizations should be made elsewhere, such as limiting object creation and destruction, and/or other expensive operations.
Upvotes: 1
Reputation: 533660
You need to look at the context of the code. If you had tuned all object creation out of the loop and this was used heavily, switching to indexed loop can make a difference.
In your case, you clearly have a much more expensive operation creating a log string. Optimising this would make much, much more difference. (possibly 10 - 1000x more)
Upvotes: 2