-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Improving for loops #15846
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improving for loops #15846
Conversation
|
Thank you, @LuisOsv for this code suggestion. The support packages contain example code that many users find helpful, but they do not necessarily represent We actively encourage people to add the wrapper and helper code that makes sense for them to their own frameworks. |
PR Reviewer Guide 🔍Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Explore these optional code suggestions:
|
||||||||||||||
User description
🔗 Related Issues
N/A — performance and readability enhancement
💥 What does this PR do?
This PR improves performance and readability by caching the size or length of collections and arrays before entering loops.
Instead of repeatedly calling .size() or .length in the loop condition, the value is stored in a local variable and reused.
🔧 Implementation Notes
This change is based on a common Java performance recommendation highlighted in High Performance with Java by Javier Fernandez Gonzalez (O’Reilly, 2024).
The book explains that repeatedly calling methods like .size() inside loop conditions is less efficient than caching their values in local variables. This approach improves both runtime performance and code readability.
Example refactor:
Instead of:
💡 Additional Considerations
🔄 Types of changes
🧪 Tests Executed
To ensure nothing was broken by this cleanup, the following affected test targets were executed:
✅ All tests passed successfully.
PR Type
Enhancement
Description
Cache collection/array size in loops for performance
Refactor for improved code readability and maintainability
No behavioral or logic changes introduced
Applied changes across grid, remote, tools, json, and support packages
Changes walkthrough 📝
14 files
Cache argument array length before loop for efficiencyStore argument array length before loop iterationCache config list size before loop for performanceStore config list size before loop for clarityCache string length before loop for efficiencyCache array length before loop and pre-size listCache list size before loop for efficiencyCache prefix path array length before loopCache group list size before switch and loopCache annotation array length before loopCache annotation array length before loopCache parameter array length before loop and comparisonCache locator array length before loop and checksCache substring array length before loop for efficiency