Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Always use iterators when iterating lists:

Tip

Do this:

Code Block
languagegroovy
for(item in items){
  doSomething(item)
}
Code Block
items.forEach.each { item ->
    doSomething(item)
}

Avoid the use of get() and getAt() – as these may be significantly slower.

...

Code Block
languagegroovy
for (int i = 0; i < items?.getRowCount(); ++i) {
    final item = items[i]
  doSomethingWith  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.

...