7 Proven Ways to Supercharge Java For‑Loops and Slash Execution Time
Learn how to dramatically improve Java for‑loop performance by applying seven practical techniques—including caching list size, using combined loop variables, iterating backwards, leveraging Iterator, enhanced for‑each syntax, minimizing nested loops, and moving exception handling outside—each with clear pros, cons, and code examples.
We often use time‑consuming loop operations, especially for loops. If written properly, their efficiency can be greatly improved. Below are several common for‑loop optimization methods.
First, initialize a collection:
List<String> list = new ArrayList<String>();Method 1: Conventional Unthoughtful Writing
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}Pros: common 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: the variable m has a larger scope than necessary, violating the minimal‑scope principle; the list size cannot be changed inside the loop.
Method 3: Combine Loop Variables
for (int i = 0, n = list.size(); i < n; i++) {
System.out.println(list.get(i));
}Pros: no repeated calculation and each variable’s scope follows the minimal‑range principle.
Cons: same drawbacks as Method 2 regarding scope and list modification.
Method 4: Reverse Iteration
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}Pros: no repeated calculation and minimal variable scope.
Cons: the result order is reversed, less readable, and may be unfamiliar.
Applicable when the order of displayed results 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 (JDK 1.5+)
for (Object o : list) {
System.out.println(o);
}Pros: concise and works well with generics.
Cons: not compatible with JDK 1.4 and earlier.
Method 7: Loop Nesting – Outer Small, Inner Large Principle
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10000; j++) {
// inner work
}
}This arrangement keeps the outer loop’s workload minimal while the inner loop handles the bulk of processing.
Method 8: Extract Non‑Loop Logic
// 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;
}Moving invariant calculations outside the loop reduces repeated work.
Method 9: Place Exception Handling Outside the Loop
Bad example (exception handling inside the loop):
for (int i = 0; i < 10; i++) {
try {
// work
} catch (Exception e) {
// handle
}
}Good example (exception handling wraps the loop):
try {
for (int i = 0; i < 10; i++) {
// work
}
} catch (Exception e) {
// handle
}These techniques collectively help developers write more efficient and maintainable Java loops.
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
