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.
, multiple selections available,
Related content
Groovy .collect
Groovy .collect
More like this
Groovy List & Map
Groovy List & Map
More like this
Avoid DB Queries Containing IN Clause with Thousands of Values
Avoid DB Queries Containing IN Clause with Thousands of Values
Read with this
Groovy .each
Groovy .each
More like this
Avoid Returning Big Data in Element Result
Avoid Returning Big Data in Element Result
Read with this
Performance Practices in Analytics
Performance Practices in Analytics
Read with this
Found an issue in documentation? Write to us.