Performance Comparison: for Loop vs. for-Each Loop
In the realm of looping constructs, the question of performance often arises, leading to a comparison between for loops and for-each loops.
For Loop vs. For-Each Loop
Consider the following two loops:
for (Object o: objectArrayList) { o.DoSomething(); }
for (int i=0; i<objectArrayList.size(); i++) { objectArrayList.get(i).DoSomething(); }
Performance Comparison
According to Item 46 of Joshua Bloch's "Effective Java," there is no performance penalty for using the for-each loop. Rather, it may even provide a slight advantage in certain scenarios.
Reason for Performance Improvement
The for-each loop skips the step of computing the limit of the array index multiple times. In the for loop, it is calculated with each iteration. In contrast, the for-each loop performs this calculation only once.
Conclusion
Programmers who strive for efficiency can use either for loops or for-each loops without significant concerns about performance. However, the simplicity and code readability of the for-each loop make it a more desirable choice in most situations.
The above is the detailed content of For Loop vs. For-Each Loop: Which is More Performant?. For more information, please follow other related articles on the PHP Chinese website!