Collections
Always prefer read-only view collections over mutable ones. Since read-only view collections can't be changed, you can prevent a lot of bugs that relate to multithreading and state inconsistency. If you need to iterate elements of an ArrayList
, consider the while
loop:
inline fun <reified T> List<T>.foreach(crossinline invoke: (T) -> Unit): Unit { val size = size var i = 0 while (i < size) { invoke(get(i)) i ++ } }
Sequences can improve performance significantly, especially if you use methods such as first
:
@Benchmark fun sequence() = (0..1_000_000) .asSequence() .filter { it % 2 == 0 } .map { it * it } .first()