Say Hello to Kotlin Sequence

In some case, sequence operation is faster than collection operation.

val list1 = (1..10_000_000)
    .filter { it % 2 == 0 }
    .map { it * 10 }
    .map { it.toString() }
    .size // 5,000,000
// took 1,263 milliseconds in my environment
val list2 = (1..10_000_000)
    .asSequence()
    .filter { it % 2 == 0 }
    .map { it * 10 }
    .map { it.toString() }
    .toList()
    .size // 5,000,000
// took 1,015 milliseconds in my environment

In this case, you can create Sequence directly like this:

val list3 = generateSequence(1) { it + 1 }
    .take(10_000_000)
    .filter { it % 2 == 0 }
    .map { it * 10 }
    .map { it.toString() }
    .toList()
    .size // 5,000,000
// took 861 milliseconds in my environment

Sequence executes lazily and does not create intermediate products.

Sequence need some overhead, so be care it is not always faster than Collection.

筆者

茨城県つくば市在住のソフトウェアエンジニアです。得意領域はAndroidとFlutterです。「Jetpack ComposeによるAndroid MVVMアーキテクチャ入門」の著者です。

👉もっと詳しく