-1

I am currently trying to figure out what's most efficient, implementing an iterator or a for each-loop.

The object that will be traversed is a class 'Graph', which is extended by a sub-class 'Graph.Vertex'. What should be most time efficient, iterating through the objects with an iterator or with a for each-loop:

Graph.iterator();
while (Graph.iterator().hasNext()) {
    // Do something
}

vs.

for (Graph.Vertex v : Graph {
    // Do something
}
robinskafte
  • 61
  • 1
  • 10
  • 8
    Neither, a for-each loop uses an iterator under the covers. – azurefrog Jan 29 '16 at 01:40
  • 3
    As the @azurefrog mentioned, both should have similar running time. That being said, using an iterator directly might allow you to do a remove during the iteration, while for each will not. – Tim Biegeleisen Jan 29 '16 at 01:42

1 Answers1

0

This entirely depends on how you implement either of these.

The usual implementations of graphs make use of arrays to store vertices and will take only O(V) time for iteration where V is the number of vertices in the graph.

If your implementation differs from this, then you must supply more information in order to get an accurate answer as to the efficiency.

smac89
  • 39,374
  • 15
  • 132
  • 179