10+ Proven Ways to Supercharge Java for‑Loops for Faster Code
This article outlines over ten practical techniques for optimizing Java for‑loops, including caching list size, using reverse iteration, employing iterators, leveraging enhanced for‑each loops, minimizing method calls, and handling exceptions efficiently, helping developers write cleaner and more performant code.
In everyday development, inefficient for‑loops can become performance bottlenecks; this guide summarizes more than ten common optimizations to make your code elegant and fast.
List<String> list = new ArrayList<String>();Method 1: Straightforward loop without optimization
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}Pros: familiar and easy to understand.
Cons: list.size() is evaluated on every iteration.
Method 2: Cache list size in a variable
int m = list.size();
for (int i = 0; i < m; i++) {
System.out.println(list.get(i));
}Pros: avoids repeated size calculation.
Cons: variable m has a broader scope than necessary and you cannot modify the list size inside the loop.
Method 3: Cache size and use two loop variables
for (int i = 0, n = list.size(); i < n; i++) {
System.out.println(list.get(i));
}Pros: no repeated size calculation; respects minimal scope.
Cons: same scope issue as method 2 and cannot change list size during iteration.
Method 4: Reverse iteration
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}Pros: no repeated size calculation; minimal variable scope.
Cons: results are produced in reverse order, which may be less readable.
Applicable when order does not matter, e.g., validation before saving.
Method 5: Iterator traversal
for (Iterator<String> it = list.iterator(); it.hasNext();) {
System.out.println(it.next());
}Pros: concise.
Method 6: Enhanced for‑each loop (Java 1.5+)
for (Object o : list) {
System.out.println(o);
}Pros: concise syntax with generics.
Cons: not compatible with Java 1.4 and earlier; cannot directly access the index.
Method 7: Nested loops following outer‑small, inner‑large principle
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10000; j++) {
// inner work
}
}Reasoning illustrated in the diagram below:
Method 8: Extract invariant logic out of the loop
// 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 {
// work
} catch (Exception e) {
// handle
}
}Good example (exception outside loop):
try {
for (int i = 0; i < 10; i++) {
// work
}
} catch (Exception e) {
// handle
}Note: If an exception should not abort the loop, keep handling inside the loop.
Method 10: Reverse deletion to avoid index shift
When removing elements without an iterator, iterate backwards:
for (int i = list.size() - 1; i >= 0; i--) {
// loop body
list.remove(i);
}Method 11: Reduce method calls inside the loop
Cache results of frequently called methods before the loop:
int size = list.size();
int result = calculateResult();
for (int i = 0; i < size; i++) {
// use cached result
}These subtle details may seem minor individually, but accumulated they can significantly impact system performance, so developers should pay attention to them during daily coding.
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 Interview Crash Guide
Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.
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.
