-4

I have algorithm with for loops, that looks like:

for(A : collection) {
  for (B : A.collection) {
     for (C : B.collection) {
        do something with C instance
     } 
  } 
}

What is the best way to optimize the performance of this nested for loops?

For example use LinkedHashMap?

Thank you.

VatsalSura
  • 926
  • 1
  • 11
  • 27
Ondra Pala
  • 59
  • 1
  • 1
  • 2
  • Fastest collection is native array - if you can use array with for(;;) loop - it will be fastest. – Oleg Imanilov Jul 21 '16 at 19:18
  • Please consider revising the code sample you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. -1, don't take it the wrong way. A down vote is how we indicate a content problem around here; improve your formatting and code sample and I'll gladly revert it. Good luck with your code! – Filip Allberg Jul 21 '16 at 19:19

1 Answers1

1

It is very likely that the program will spend most of its time in the do something with C instance part. In this case, optimizations will probably not be worthwhile.

Aside from that, iteration speed depends on the type of collection. Arrays and ArrayList are fastest. Iteration over LinkedList and most other containers are slower because element access requires additional indirections. The Vector is also slower because of synchronization overhead.

Optimization will be most effective for the inner loop because it will be executed more often than the outer ones.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45