The best way in Java:
for (Integer i : calc.subList(start, calc.size()) { ... }
subList is an efficient view of the source list, so you almost certainly need it.
UPDATE
OK, motivated by Mikera's comments, I compared it on jmh . This is the control code:
import org.openjdk.jmh.annotations.GenerateMicroBenchmark; public class Benchmark1 { static final List<Integer> list = new ArrayList(asList(1,2,3,4,5,6,7,8,9,10)); static { for (int i = 0; i < 5; i++) list.addAll(list); } @GenerateMicroBenchmark public long testIterator() { long sum = 0; for (int i : list) sum += i; return sum; } @GenerateMicroBenchmark public long testIndexed() { long sum = 0; for (int i = 0; i < list.size(); i++) sum += list.get(i); return sum; } @GenerateMicroBenchmark public long testSublistIterator() { long sum = 0; for (int i : list.subList(1, list.size())) sum += i; return sum; } @GenerateMicroBenchmark public long testIndexedSublist() { long sum = 0; final List<Integer> l = list.subList(1, list.size()); for (int i = 0; i < l.size(); i++) sum += l.get(i); return sum; } }
And here are the results:
Benchmark ops/msec ------------------------- Indexed 1860.982 IndexedSublist 1642.059 Iterator 1818.657 SublistIterator 1496.994
Conclusions:
extended for the main list, it performs as fast as the indexed iteration, once after the initialization cost;
subscriber traversal is somewhat slower than the main list, and iteration is somewhat slower than the indexed traversal;
all differences are insignificant for all practical purposes.
Marko topolnik
source share