Kotlin › Practice

Benchmarking Kotlin Sequence vs. Iterable and inline with JMH

JMH and -prof gc benchmarks of Kotlin Sequence vs. Iterable pipelines on JDK 17, plus javap bytecode analysis of inline and reified functions.

Benchmarking Kotlin Sequence vs. Iterable and inline with JMH

During an algorithm study group, someone claimed that chaining collection operations is always faster when you add asSequence(). I wanted real numbers instead of rules of thumb, so I benchmarked Sequence and Iterable pipelines with JMH across collection sizes and terminal operations, then inspected what inline and reified actually change in bytecode.

Test environment: Kotlin 1.9.0, JDK 17 (Temurin 17.0.16 via Gradle toolchain), Gradle 8.2.1, me.champeau.jmh 0.7.1, and JMH 1.36. Numbers are the median of 3 runs on a personal PC (12 cores, 32 GB RAM, Windows with Docker Desktop/WSL2) using 2 forks, 3 warmup iterations of 1s, and 5 measurement iterations of 1s. Background CPU usage fluctuated between 0% and 85%, so read these numbers as ratios rather than absolute timings.

Background

In my study assignments, I wrote a lot of chained pipelines like map { }.filter { }.first { }. The usual advice says “use Sequence for large collections and Iterable for small ones,” but nobody ever pins down what “large” means or how much the terminal operation changes the picture.

To find where the crossover actually sits, I set up a JMH benchmark on a List<Int> with 100, 10,000, and 1,000,000 elements. I tested three pipeline shapes: full aggregation (sum()), collecting back into a list (toList()), and short-circuiting (first { }). Alongside runtime, I attached -prof gc to measure normalized memory allocation per operation.

How Iterable and Sequence work

Iterable evaluates every stage eagerly. When you call map followed by filter, each operator loops through the entire input and allocates a brand-new ArrayList for its output. The upside is that both Iterable.map and Iterable.filter are marked inline, so the Kotlin compiler flattens your lambdas directly into the call site without creating function objects.

Sequence evaluates lazily. Sequence.map is not inline—it wraps the upstream sequence and stores your lambda as a field inside a TransformingSequence object. Nothing runs until a terminal operation pulls from the iterator. At that point, a single element travels through map, then filter, then the terminal check before the next element starts.

flowchart TD
    A["Source List"] --> B{"Evaluation mode"}
    B -->|"Iterable"| C["Allocate ArrayList for map"]
    C --> D["Allocate ArrayList for filter"]
    B -->|"Sequence"| E["Push one item through map and filter"]
    E --> F["Stop immediately when terminal matches"]

That design gives Sequence two structural advantages: it skips intermediate list allocations, and short-circuiting operators like first stop without touching the rest of the input. The trade-off is extra per-element indirection through nested iterators and Function1.invoke calls.

Benchmark setup and results

I used the me.champeau.jmh Gradle plugin to run JMH benchmarks inside the project with -prof gc enabled. Because JMH generates subclasses of your benchmark class at build time, the Kotlin class must be declared open.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// build.gradle.kts
plugins {
    kotlin("jvm") version "1.9.0"
    id("me.champeau.jmh") version "0.7.1"
}

repositories { mavenCentral() }

kotlin { jvmToolchain(17) }

jmh {
    jmhVersion.set("1.36")
    fork.set(2)
    warmupIterations.set(3)
    warmup.set("1s")
    iterations.set(5)
    timeOnIteration.set("1s")
    benchmarkMode.set(listOf("avgt"))
    profilers.set(listOf("gc"))
    resultFormat.set("JSON")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// src/jmh/kotlin/bench/PipelineBenchmark.kt
package bench

import java.util.concurrent.TimeUnit
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.OutputTimeUnit
import org.openjdk.jmh.annotations.Param
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.Setup
import org.openjdk.jmh.annotations.State

@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
open class PipelineBenchmark {
    @Param("100", "10000", "1000000")
    var size: Int = 0

    private lateinit var data: List<Int>

    @Setup
    fun setup() {
        data = List(size) { it }
    }

    @Benchmark
    fun fullIterable(): Int = data.map { it * 2 }.filter { it % 3 == 0 }.sum()

    @Benchmark
    fun fullSequence(): Int = data.asSequence().map { it * 2 }.filter { it % 3 == 0 }.sum()

    @Benchmark
    fun toListIterable(): List<Int> = data.map { it * 2 }.filter { it % 3 == 0 }

    @Benchmark
    fun toListSequence(): List<Int> = data.asSequence().map { it * 2 }.filter { it % 3 == 0 }.toList()

    // The first matching element sits near the middle of the list (around size / 2)
    @Benchmark
    fun firstIterable(): Int = data.map { it * 2 }.filter { it % 3 == 0 }.first { it > size }

    @Benchmark
    fun firstSequence(): Int = data.asSequence().map { it * 2 }.filter { it % 3 == 0 }.first { it > size }
}

Running ./gradlew jmh across all parameter combinations produced the median numbers below. Allocation figures come from -prof gc (gc.alloc.rate.norm) and were nearly identical across all three runs.

PipelineSizeIterableSequenceIterable / SequenceAllocation (Iterable -> Sequence)
map · filter · sum1000.657 µs0.292 µs2.2x1,648 B -> 672 B
map · filter · sum10,00050.5 µs29.4 µs1.7x249 KB -> 159 KB
map · filter · sum1,000,00010.44 ms5.95 ms1.8x24.3 MB -> 16.0 MB
map · filter · toList1000.560 µs0.379 µs1.5x1,648 B -> 1,304 B
map · filter · toList10,00045.0 µs43.4 µs1.0x249 KB -> 209 KB
map · filter · toList1,000,0008.52 ms6.92 ms1.2x24.3 MB -> 20.3 MB
map · filter · first1000.467 µs0.170 µs2.7x1,648 B -> 108–120 B
map · filter · first10,00045.8 µs15.8 µs2.9x249 KB -> 79 KB
map · filter · first1,000,00010.76 ms1.83 ms5.9x24.3 MB -> 8.0 MB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "type": "bar",
  "data": {
    "labels": ["map · filter · sum", "map · filter · toList", "map · filter · first"],
    "datasets": [
      { "label": "Iterable (ms)", "data": [10.44, 8.52, 10.76], "backgroundColor": "#7aa2f7" },
      { "label": "Sequence (ms)", "data": [5.95, 6.92, 1.83], "backgroundColor": "#9ece6a" }
    ]
  },
  "options": {
    "plugins": { "title": { "display": true, "text": "1M-element List<Int> pipeline runtime (median of 3 runs)" } },
    "scales": { "y": { "beginAtZero": true, "title": { "display": true, "text": "ms/op" } } }
  }
}

Two results surprised me. First, Sequence was already faster at just 100 elements. With two chained stages, allocating two intermediate ArrayLists cost more than stepping through the sequence iterators. Second, collecting into a list with toList() shrank the gap to 1.0–1.5x. You still have to allocate the final list either way, and because Sequence doesn’t know the final size upfront, the backing array grows and copies repeatedly as elements arrive.

You might also wonder why the 1,000,000-element Sequence run still allocated 16.0 MB during sum(). Every result of map { it * 2 } above 127 exceeds the JVM Integer cache and boxes into a fresh 16-byte Integer object. The 8.0 MB figure for first matches that math: the sequence stopped halfway through, right around 500,000 elements. Because some individual cells had ±30% within-run variance on this machine, I treat small ratios like 1.0–1.2x as roughly tied.

Bytecode and runtime cost of inline and reified

Next, I inspected what inline and reified remove from the compiled bytecode using javap -c -p.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/main/kotlin/inl/Inline.kt
package inl

inline fun <reified T> List<Any>.countOf(): Int {
    var count = 0
    for (e in this) if (e is T) count++
    return count
}

fun countStrings(xs: List<Any>): Int = xs.countOf<String>()

fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))

inline fun applyTwiceInline(x: Int, f: (Int) -> Int): Int = f(f(x))

fun callNonInline(base: Int): Int = applyTwice(3) { it + base }

fun callInline(base: Int): Int = applyTwiceInline(3) { it + base }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static final int countStrings(java.util.List<? extends java.lang.Object>);
      41: instanceof    #51                 // class java/lang/String

public static final int callNonInline(int);
       1: new           #85                 // class inl/InlineKt$callNonInline$1
       6: invokespecial #89                 // Method inl/InlineKt$callNonInline$1."<init>":(I)V
      12: invokestatic  #91                 // Method applyTwice:(ILkotlin/jvm/functions/Function1;)I

public static final int callInline(int);
       9: iload_3
      10: iload_0
      11: iadd
      16: iload_3
      17: iload_0
      18: iadd

callNonInline allocates a capturing lambda instance (InlineKt$callNonInline$1) with new on every call, and its invoke method boxes the integer result via Integer.valueOf. In callInline, all of that disappears—only two iadd instructions remain. For reified, the compiler emits instanceof String directly inside countStrings. Meanwhile, the standalone countOf method body keeps only a reifiedOperationMarker and an instanceof Object placeholder, which is why Java callers can’t invoke a reified function meaningfully.

At runtime, the actual cost of the non-inline lambda depended entirely on what the JIT compiler did:

ApproachTimeAllocation
Kotlin inline0.29 ns/op0 B/op
Regular higher-order function, JIT inlining allowed0.24 ns/op0 B/op
Regular higher-order function, -XX:CompileCommand=dontinline2.83 ns/op24 B/op

When HotSpot JIT inlines applyTwice, escape analysis eliminates the lambda allocation completely, leaving no measurable gap against Kotlin inline. Once I blocked JIT inlining, every call allocated a 24-byte lambda object and slowed down by roughly 10x. That’s the scenario Kotlin inline protects you from: megamorphic call sites or large methods where the JIT gives up on inlining.

When to use Sequence—and when not to

ScenarioRecommendationReason
Short-circuiting (first, find, take)Sequence5.9x faster and 1/3 the allocation at 1M items
Multi-step full scan into scalar aggregationSequence1.7–2.2x faster with no intermediate lists
Collecting final output into toList()EitherOnly 1.0–1.5x difference; resizing narrows the gap
Single stage (e.g., map alone)IterableNo intermediate collection to eliminate
Pipeline includes sorted, groupBy, or distinctPrefer IterableSequence still buffers everything internally

There are clear cases where you shouldn’t reach for Sequence. Stateful operations like sorted() collect the entire stream into a list before sorting, throwing away lazy evaluation. Iterating the same Sequence twice re-runs the whole pipeline from scratch, and a seedless generateSequence { } throws IllegalStateException on a second pass. Finally, if primitive-heavy loops sit on your hot path, neither List<Int> nor Sequence<Int> avoids boxing—start with an IntArray and a plain for loop instead.

Caveats and checklist

Watch out for @CompilerControl(DONT_INLINE) in Kotlin JMH benchmarks. Under this setup (JMH 1.36 with the default reflection generator), @CompilerControl was silently ignored because it has CLASS retention and isn’t visible via reflection, leaving META-INF/CompilerHints empty. Switching to the asm generator failed because it couldn’t parse Java 17 class files (major version 61). I initially got a misleading 0.2 ns result before passing -XX:CompileCommand=dontinline,... via jvmArgsAppend to force a real non-inlined measurement.

  • Prioritize asSequence() on chained pipelines that short-circuit (first, find, take).
  • Don’t blindly convert toList() pipelines to Sequence without measuring first.
  • Check that sorted(), groupBy(), or repeated iteration aren’t quietly defeating lazy evaluation.
  • Mark stored or forwarded lambda parameters as noinline when writing inline higher-order utilities.
  • Treat sub-nanosecond timings or 0 B/op allocations in JMH with suspicion until you verify the JIT didn’t inline or fold away the work.
This post is licensed under CC BY 4.0 by the author.