Performance

suggest change

Kotlin on the JVM compiles to bytecode that is about as fast as the equivalent Java. The compiler does very little optimization itself; the JIT compiler in the JVM does the heavy lifting at run time. What decides whether Kotlin code is fast is mostly the code you write: which data structures you pick, how much garbage you create, whether numbers get boxed and whether lambdas get inlined.

This article covers:

To find where a program is slow (JFR, async-profiler, flame graphs, heap dumps) see Profiling. The workflow is always the same: profile to find the hotspot, make one change, then measure again with a profiler or a benchmark.

Rules of thumb

  1. Measure before optimizing. Most code is not hot. A 10x speed-up of a function that takes 1% of the time is invisible.
  2. Algorithms first. Replacing an O(n²) list.contains loop with a HashSet beats any micro-optimization.
  3. Allocation is the usual suspect. Allocating is cheap on the JVM, but a high allocation rate means more GC work and worse cache behavior. Boxing, intermediate lists and string concatenation are the common sources.
  4. Keep readable code where it isn't hot. The tricks below make code uglier; use them only where a profile or benchmark says they pay off.

Benchmarking with JMH

Timing code with measureTime in a loop is misleading for small pieces of code. The JVM interprets code before compiling it, recompiles it when its assumptions change, removes computations whose results are unused and folds constants. JMH (Java Microbenchmark Harness) handles warm-up, forking, dead-code elimination and statistics for you.

The easiest way to use JMH from a Kotlin Gradle project is the kotlinx-benchmark plugin:

// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.allopen") version "2.4.21"
    id("org.jetbrains.kotlinx.benchmark") version "0.5.0"
}

repositories { mavenCentral() }

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-benchmark-runtime:0.5.0")
}

// JMH generates subclasses of benchmark classes, so they must be open
allOpen {
    annotation("org.openjdk.jmh.annotations.State")
}

benchmark {
    targets {
        register("main")
    }
    configurations {
        named("main") {
            warmups = 3             // warm-up iterations
            iterations = 5          // measured iterations
            iterationTime = 1
            iterationTimeUnit = "s"
        }
    }
}

A benchmark is a class annotated with @State whose @Benchmark methods are measured:

// src/main/kotlin/bench/SumBenchmark.kt
package bench

import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import kotlin.random.Random

@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(1)
class SumBenchmark {
    @Param("1000", "100000")
    var size: Int = 0

    private lateinit var array: IntArray
    private lateinit var list: List<Int>

    @Setup
    fun setup() {
        val rnd = Random(42)
        array = IntArray(size) { rnd.nextInt(1000) }
        list = array.toList()
    }

    @Benchmark
    fun intArraySum(): Int = array.sum()

    @Benchmark
    fun listSum(): Int = list.sum()

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

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

    @Benchmark
    fun loopFilterMap(): Int {
        var sum = 0
        for (x in array) if (x % 2 == 0) sum += x * 3
        return sum
    }
}

Run it with ./gradlew benchmark. JMH prints a table at the end and kotlinx-benchmark writes a JSON report to build/reports/benchmarks/main/:

Benchmark                        (size)  Mode  Cnt    Score    Error  Units
SumBenchmark.intArraySum           1000  avgt    5    0.071 ±  0.002  us/op
SumBenchmark.intArraySum         100000  avgt    5    7.012 ±  0.115  us/op
SumBenchmark.listSum               1000  avgt    5    0.583 ±  0.010  us/op
SumBenchmark.listSum             100000  avgt    5   78.904 ±  2.731  us/op
SumBenchmark.listFilterMap         1000  avgt    5    4.218 ±  0.090  us/op
SumBenchmark.listFilterMap       100000  avgt    5  611.337 ± 14.502  us/op
SumBenchmark.loopFilterMap         1000  avgt    5    0.402 ±  0.008  us/op
SumBenchmark.loopFilterMap       100000  avgt    5   49.770 ±  0.933  us/op
SumBenchmark.sequenceFilterMap     1000  avgt    5    2.311 ±  0.041  us/op
SumBenchmark.sequenceFilterMap   100000  avgt    5  305.125 ±  6.284  us/op

(Your numbers will differ; the proportions are what matter.) Summing an IntArray is about 10x faster than summing a List<Int> of the same numbers, because the list holds pointers to boxed Integer objects scattered in memory. The sequence beats the eager list chain because it doesn't build two intermediate lists, and the plain loop over primitives beats both.

If you don't want kotlinx-benchmark, the me.champeau.jmh Gradle plugin runs JMH directly on sources in src/jmh/kotlin (./gradlew jmh), and JMH also has a Maven archetype.

Benchmark pitfalls

Return or consume every result. If a benchmark computes a value and throws it away, the JIT may delete the computation and you measure nothing. Return the value from the @Benchmark method, or pass it to a Blackhole when there are several:

import org.openjdk.jmh.infra.Blackhole

@Benchmark
fun parseAll(bh: Blackhole) {
    for (s in inputs) bh.consume(s.toIntOrNull())
}

Don't benchmark constants. fun f() = "42".toInt() lets the JIT see a constant input. Keep inputs in @State fields initialized in @Setup, as size, array and list are above.

Don't loop inside the benchmark to make the operation "long enough". JMH already calls the method millions of times; a manual loop invites the JIT to optimize across iterations in ways real code never sees.

Use @Param to test several input sizes. Performance often flips between small and large inputs (a linear scan of 8 elements beats a hash lookup; of 10,000 elements it doesn't).

Compare against a baseline and look at the error column. A difference smaller than the Error interval is noise.

Boxing

Int, Long, Double, Boolean and Char compile to JVM primitives (int, long, ...) when possible. They become heap objects (java.lang.Integer etc.) when:

Boxing costs an allocation (values from -128 to 127 are cached and free) and an extra pointer dereference on every read. On 64-bit HotSpot an Integer takes 16 bytes plus a 4-byte reference to it, versus 4 bytes for an int in an IntArray:

import com.sun.management.ThreadMXBean
import java.lang.management.ManagementFactory

val threadBean = ManagementFactory.getThreadMXBean() as ThreadMXBean

inline fun allocated(label: String, block: () -> Any) {
    val before = threadBean.currentThreadAllocatedBytes
    val result = block()
    val bytes = threadBean.currentThreadAllocatedBytes - before
    println("%-10s %5.1f MB  (%s)".format(label, bytes / 1_000_000.0, result.javaClass.simpleName))
}

fun main() {
    val n = 1_000_000
    allocated("IntArray") { IntArray(n) { it } }
    allocated("List<Int>") { List(n) { it } }
}
IntArray     4.0 MB  (int[])
List<Int>   20.0 MB  (ArrayList)

Five times the memory for the same numbers, and a million objects for the GC to trace. Ways to avoid boxing:

fun interface IntOp {
    fun apply(x: Int): Int     // compiles to apply(I)I: no boxing
}

fun applyAll(values: IntArray, op: IntOp): IntArray =
    IntArray(values.size) { op.apply(values[it]) }

fun applyAllBoxed(values: IntArray, op: (Int) -> Int): IntArray =
    IntArray(values.size) { op(values[it]) }   // boxes argument and result for values > 127

fun main() {
    val doubled = applyAll(intArrayOf(1, 200, 3000)) { it * 2 }
    println(doubled.joinToString())
}
2, 400, 6000

(If applyAll were an inline function the lambda would be inlined and there would be no boxing either way.)

A classic hidden case is counting with a Map<String, Int>: counts[k] = (counts[k] ?: 0) + 1 does two hash lookups and allocates a new Integer for every increment above 127. A tiny mutable counter does one lookup and no allocation per increment:

class Counter { var n = 0 }

fun countWords(words: List<String>): Map<String, Int> {
    val counts = HashMap<String, Counter>()
    for (w in words) counts.getOrPut(w) { Counter() }.n++
    return counts.mapValues { it.value.n }
}

fun main() {
    val words = "the cat and the dog and the bird".split(" ")
    println(countWords(words).toSortedMap())
}
{and=2, bird=1, cat=1, dog=1, the=3}

For readable code that isn't hot, words.groupingBy { it }.eachCount() is the idiomatic choice.

Choosing collections

Kotlin's collection factories hide the concrete JVM classes. It helps to know what you get:

fun main() {
    println(listOf(1, 2, 3).javaClass.name)
    println(mutableListOf<Int>().javaClass.name)
    println(mutableSetOf<Int>().javaClass.name)
    println(mutableMapOf<String, Int>().javaClass.name)
    println(hashSetOf<Int>().javaClass.name)
    println(hashMapOf<String, Int>().javaClass.name)
    println(sortedMapOf<String, Int>().javaClass.name)
    println(ArrayDeque<Int>().javaClass.name)
}
java.util.Arrays$ArrayList
java.util.ArrayList
java.util.LinkedHashSet
java.util.LinkedHashMap
java.util.HashSet
java.util.HashMap
java.util.TreeMap
kotlin.collections.ArrayDeque

setOf, mutableSetOf, mapOf, mutableMapOf and functions like toSet(), associate and groupBy all return linked hash collections, which preserve insertion order at the cost of two extra references per entry. When order doesn't matter and the collection is large or hot, use HashMap/HashSet (hashMapOf, toHashSet(), associateTo(HashMap()) { ... }).

Need Use Avoid
indexed list, append at end ArrayList (mutableListOf) java.util.LinkedList (slow iteration, 24+ bytes per node)
queue or stack, add/remove at both ends ArrayDeque list.removeAt(0) on an ArrayList (O(n) shift)
membership test (in) HashSet List.contains in a loop (O(n) each)
key lookup HashMap list.find { it.id == id } in a loop
sorted keys, range queries TreeMap / sortedMapOf sorting a list after every insert
many numbers IntArray, primitive collections List<Int>, Map<Int, Int>
enum keys EnumMap, EnumSet HashMap with enum keys

The most common real-world speed-up is replacing repeated linear searches with a lookup structure built once:

data class User(val id: Int, val name: String)
data class Order(val userId: Int, val total: Double)

// O(orders * users): scans the user list for every order
fun slowNames(orders: List<Order>, users: List<User>) =
    orders.map { o -> users.first { it.id == o.userId }.name }

// O(orders + users): one HashMap, one lookup per order
fun fastNames(orders: List<Order>, users: List<User>): List<String> {
    val byId = users.associateByTo(HashMap(users.size * 2)) { it.id }
    return orders.map { o -> byId.getValue(o.userId).name }
}

fun main() {
    val users = listOf(User(1, "Ann"), User(2, "Bob"))
    val orders = listOf(Order(2, 9.5), Order(1, 20.0), Order(2, 3.0))
    println(fastNames(orders, users))
}
[Bob, Ann, Bob]

Presize when you know the size

ArrayList grows by 50% and copies its array; HashMap doubles and rehashes every entry. When the final size is known, pass it up front:

val list = ArrayList<String>(n)
val list2 = buildList(n) { repeat(n) { add("item$it") } }

// HashMap(n) still resizes once n > 0.75 * capacity; this sizes it for n entries:
val map = java.util.HashMap.newHashMap<String, Int>(n)   // JDK 19+
val map2 = buildMap(n) { put("a", 1) }

Stdlib functions like map, toList, associate and toHashSet already presize their results from the source collection.

Collection operations and sequences

Each eager operation on a collection (filter, map, flatMap, sortedBy, ...) creates a complete new list. A chain of four operations over a million elements allocates four lists of up to a million elements. A few habits avoid most of that waste:

val words = listOf("kotlin", "java", "scala", "go", "rust", "kotlin")

// counting: no intermediate list
val longWords = words.count { it.length > 3 }           // not words.filter { ... }.size

// existence: stops at the first match
val hasGo = words.any { it == "go" }                     // not words.filter { ... }.isNotEmpty()

// first match: stops early
val firstLong = words.firstOrNull { it.length > 5 }      // not words.filter { ... }.firstOrNull()

// aggregate in one pass
val totalLength = words.sumOf { it.length }              // not words.map { it.length }.sum()

// map + filter-nulls in one pass
val lengths = words.mapNotNull { if (it.length > 3) it.length else null }

// write into an existing collection instead of creating a new one
val unique = words.filterTo(HashSet()) { it.length > 2 }

fun main() {
    println("$longWords $hasGo $firstLong $totalLength $lengths ${unique.size}")
}
5 true kotlin 27 [6, 4, 5, 4, 6] 4

For longer chains over large collections, convert to a Sequence with asSequence(). Sequences are lazy: each element flows through the whole chain before the next one starts, so there are no intermediate lists and operations like first or take stop early (see Sequences for how evaluation works).

val result = hugeList.asSequence()
    .filter { it.isActive }
    .map { it.score * weight }
    .filter { it > threshold }
    .take(100)
    .toList()

Sequences are not automatically faster:

Java's IntStream/LongStream avoid boxing and can run in parallel (.parallel()), which can help for CPU-heavy work over very large arrays.

Inline functions and lambdas

Passing a lambda to a regular higher-order function creates a function object (unless the lambda captures nothing, in which case a single instance is reused) and calls it through an interface. Since Kotlin 2.0, lambdas are compiled with invokedynamic, which makes them cheaper to load, but a capturing lambda still allocates an object per call.

inline functions avoid all of that: the compiler copies the function body and the lambda body into the caller. That's why stdlib functions like map, filter, forEach, let, apply, use, repeat and synchronized cost nothing compared to a hand-written loop. See Inline Functions for the language details.

Make your own small higher-order helpers inline when they are called in hot code:

import kotlin.time.TimeSource

// inline: no Function object, `block` can return from the caller, works with suspend calls
inline fun <T> timed(label: String, block: () -> T): T {
    val mark = TimeSource.Monotonic.markNow()
    val result = block()
    println("$label took ${mark.elapsedNow()}")
    return result
}

inline fun IntArray.sumIf(predicate: (Int) -> Boolean): Int {
    var sum = 0
    for (x in this) if (predicate(x)) sum += x   // predicate is inlined: no boxing, no call
    return sum
}

fun main() {
    val data = IntArray(1_000) { it }
    val threshold = 900
    val s = timed("sumIf") { data.sumIf { it > threshold } }
    println(s)
}
sumIf took 41.2us    (timing varies by machine)
94050

Don't inline everything: inlining large functions bloats every call site, and functions without lambda parameters gain nothing (the JIT already inlines small methods). Use noinline for lambda parameters that are stored or passed on, and crossinline for ones called from another context.

Value classes

A @JvmInline value class wraps a single value for type safety without allocating a wrapper object in most cases:

@JvmInline
value class Meters(val value: Double) {
    operator fun plus(other: Meters) = Meters(value + other.value)
}

fun total(segments: DoubleArray): Meters {
    var sum = Meters(0.0)                       // a plain double at run time
    for (s in segments) sum += Meters(s)
    return sum
}

fun main() {
    println(total(doubleArrayOf(1.5, 2.25, 3.0)))
}
Meters(value=6.75)

Like primitives, a value class is boxed when used as a nullable type (Meters?), as a type argument (List<Meters>) or as an interface type. Keep hot paths on the non-nullable, non-generic form.

Reducing allocation

Build strings with buildString or StringBuilder, not += in a loop, which copies the whole string every time:

fun report(counts: Map<String, Int>): String = buildString(counts.size * 16) {
    for ((word, n) in counts) {
        append(word).append(": ").append(n).append('\n')
    }
}

fun main() {
    print(report(mapOf("kotlin" to 3, "java" to 1)))
}
kotlin: 3
java: 1

String templates ("$a: $b") compile to a StringBuilder or StringConcatFactory call and are fine for a single string. joinToString is fine for joining a collection. String.format is much slower than templates; avoid it in hot loops.

Compile regular expressions once. Regex("...") inside a function compiles the pattern on every call; store it in a top-level or companion val. The Profiling article shows this exact bug taking 90% of a program's time.

Pick the right lazy mode. by lazy { } is synchronized by default. For values only touched from one thread use lazy(LazyThreadSafetyMode.NONE) { }, and PUBLICATION when computing the value twice is harmless.

Don't use exceptions for control flow. Creating an exception captures a stack trace, which is expensive. Use the stdlib's non-throwing variants:

fun main() {
    val inputs = listOf("12", "x", "7", "", "40")
    val numbers = inputs.mapNotNull { it.toIntOrNull() }   // not try { it.toInt() } catch ...
    println(numbers.sum())
    println(numbers.getOrNull(10) ?: -1)                    // not catching IndexOutOfBounds
}
59
-1

Avoid Pair/Triple and destructuring of data classes in very hot loops when the objects don't escape anyway: returning Pair(a, b) from a function called a billion times allocates a billion pairs unless the JIT's escape analysis removes them. A value class or two out-parameters (e.g. writing into an array) avoid it. Destructuring itself (val (a, b) = pair) is free; it just calls component1() and component2().

Loops over ranges are free; ranges as objects are not. for (i in 0 until n), for (i in list.indices), for (i in n downTo 0 step 2), for (x in array) and repeat(n) compile to plain counting loops. But (0 until n).map { } allocates a list, and storing a range in a variable of type Iterable<Int> boxes on iteration.

vararg allocates an array on every call, and the spread operator (*array) copies the array. For hot functions provide overloads for the common arities.

Use const val for compile-time constants. A const val is inlined at the use site; a plain val in a companion object goes through a getter (which the JIT will usually inline, but const is simpler).

Concurrency

Parallelism helps only for CPU-bound work that can be split:

JVM settings

Some performance comes from how the program runs, not how it's written:

Checklist

When a profile points at a piece of Kotlin code:

  1. Is there a better algorithm or data structure (a HashMap instead of a linear search, a Set instead of List.contains)?
  2. Are numbers boxed (List<Int>, Int?, Map<_, Int>, (Int) -> Int)? Use primitive arrays, primitive collections or a mutable counter.
  3. Does a chain of collection operations build large intermediate lists? Combine steps (count, sumOf, mapNotNull), use a sequence, or write a loop.
  4. Is something expensive created repeatedly (a Regex, a formatter, a String built with +=, an exception)? Create it once or use a cheaper alternative.
  5. Is a hot higher-order helper non-inline? Make it inline.
  6. Are collections growing from empty when the size is known? Presize them.
  7. Write a JMH benchmark for the before and after, and keep the change only if the numbers improve.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents