DEV Community

okuzawats
okuzawats

Posted on • Edited on

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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Sequence executes lazily and does not create intermediate products.

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

Top comments (0)