/
Iterating Collections

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.

 

Related content

Caching Strategies in Configuration
Caching Strategies in Configuration
Read with this
Avoid DB Queries Containing IN Clause with Thousands of Values
Avoid DB Queries Containing IN Clause with Thousands of Values
Read with this
Use Correct Product/Customer Extensions Size
Use Correct Product/Customer Extensions Size
Read with this

Found an issue in documentation? Write to us.