0
0
Kotlinprogramming~5 mins

Sequence vs collection performance in Kotlin

Choose your learning style9 modes available
Introduction
Sequences and collections help you handle groups of data. Knowing their performance helps you choose the best one for your task.
When you want to process large lists without using much memory.
When you need to perform many operations on data step-by-step.
When you want faster results by avoiding creating many temporary lists.
When you have small data and want simple, direct access.
When you want to chain multiple operations efficiently.
Syntax
Kotlin
val mySequence = sequenceOf(1, 2, 3)
val myList = listOf(1, 2, 3)
Sequences process elements one by one, which can save memory.
Collections like lists hold all elements in memory at once.
Examples
This creates a new list by doubling each number immediately.
Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
This creates a sequence that will double numbers only when needed.
Kotlin
val numbersSeq = sequenceOf(1, 2, 3, 4, 5)
val doubledSeq = numbersSeq.map { it * 2 }
Filters even numbers from the sequence and converts to a list.
Kotlin
val result = numbersSeq.filter { it % 2 == 0 }.toList()
Sample Program
This program compares time taken to process a large list using collections and sequences. It doubles numbers and filters those divisible by 3.
Kotlin
import kotlin.system.measureTimeMillis

fun main() {
    val numbers = (1..1_000_000).toList()

    val timeList = measureTimeMillis {
        val doubled = numbers.map { it * 2 }
        val filtered = doubled.filter { it % 3 == 0 }
        println("List result size: ${filtered.size}")
    }

    val numbersSeq = numbers.asSequence()

    val timeSeq = measureTimeMillis {
        val doubledSeq = numbersSeq.map { it * 2 }
        val filteredSeq = doubledSeq.filter { it % 3 == 0 }.toList()
        println("Sequence result size: ${filteredSeq.size}")
    }

    println("List time: $timeList ms")
    println("Sequence time: $timeSeq ms")
}
OutputSuccess
Important Notes
Sequences are lazy: they do work only when needed, saving memory and sometimes time.
Collections do all work immediately, which can be faster for small data.
For big data or many chained operations, sequences usually perform better.
Summary
Sequences process data lazily, saving memory and improving performance on large data.
Collections hold all data in memory and process eagerly, good for small data.
Choose sequences for big or complex data tasks, collections for simple or small tasks.