Iterating Collections
Always use iterators when iterating lists:
Do this:
items.each { item ->
doSomething(item)
}
Avoid the use of get()
and getAt()
– as these may be significantly slower.
Never do this:
for (int i = 0; i < items?.getRowCount(); ++i)Â {
final item = items[i]
doSomething(item)
}
Not all collections are randomly accessible, but despite this, the get()
method is present on the java.util.List
interface. (Groovy adds the getAt()
method, which enables the use of the index []
operator.) Especially for large collections, the get()/getAt()
method can be notably slow. In the example above, each time the []
operator is used, the article gets iterated item-by-item until the requested element is reached. Thus, with a data
of size N
, this results in N^2
complexity.
If you need the index during the iterator, use the eachWithIndex()
method.
Â
Found an issue in documentation? Write to us.
Â