Boost Java Loop Performance: 9 Proven Optimization Techniques
This article presents nine practical ways to speed up Java for‑loops, covering simple size caching, combined index variables, reverse iteration, iterator usage, enhanced for‑loops, nesting reduction, pre‑computing constants, and moving exception handling outside the loop, each with code examples and pros‑cons.
We often use loops that perform repetitive calculations, especially for loops, which can become a performance bottleneck if not written efficiently. Below are nine common optimization methods for Java for loops.
Method 1: Straightforward Loop
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}Advantage: Simple and easy to understand.
Disadvantage: Calls list.size() on every iteration.
Method 2: Cache Size in a Variable
int m = list.size();
for (int i = 0; i < m; i++) {
System.out.println(list.get(i));
}Advantage: Avoids repeated size calculation.
Disadvantage: Variable m has a broader scope and violates the principle of minimal scope; the list size must not change during the loop.
Method 3: Cache Size with Combined Index
for (int i = 0, n = list.size(); i < n; i++) {
System.out.println(list.get(i));
}Advantage: No repeated size calculation and respects minimal scope.
Disadvantage: Same scope limitation as Method 2.
Method 4: Reverse Iteration
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}Advantage: No repeated size calculation and minimal scope.
Disadvantage: Result order is reversed and the pattern may be harder to read.
Applicable when the order of processing does not matter, e.g., validation before persisting data.
Method 5: Iterator Traversal
for (Iterator<String> it = list.iterator(); it.hasNext();) {
System.out.println(it.next());
}Advantage: Concise.
Method 6: Enhanced For‑Loop (Java 1.5+)
for (Object o : list) {
System.out.println(o);
}Advantage: Concise and works well with generics.
Disadvantage: Not compatible with Java 1.4 and earlier.
Method 7: Reduce Nested Loop Work
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10000; j++) {
}
}By moving invariant logic out of the inner loop, the total number of executions can be dramatically reduced.
Method 8: Extract Invariant Computation
// Before:
int a = 10, b = 11;
for (int i = 0; i < 10; i++) {
i = i * a * b;
}
// After:
int c = a * b;
for (int i = 0; i < 10; i++) {
i = i * c;
}Method 9: Move Exception Handling Outside the Loop
Bad example (exception inside loop):
for (int i = 0; i < 10; i++) {
try {
} catch (Exception e) {
}
}Good example (exception outside loop):
try {
for (int i = 0; i < 10; i++) {
}
} catch (Exception e) {
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
