Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 134 ยท Testing and Tooling

Kotlin Performance and Bytecode

Understand Kotlin performance: what the compiler generates, boxing of Int and List<Int>, inline functions, sequences vs lists, value classes, how to read bytecode and measure with JMH.

Kotlin code usually performs like the equivalent Java code, because both compile to the same kind of JVM bytecode. Most programs are limited by algorithms, I/O and database calls, not by language features. Still, a few Kotlin features hide work that is useful to know about: extra objects created by boxing, lambdas that allocate, intermediate lists in a chain of operations. This lesson explains where those costs come from, how to look at what the compiler generates, and how to measure before you change anything.

One rule comes first: do not optimize without measuring. Clear code in the first version, a profiler or benchmark to find the real hot spot, and only then a change. The sections below teach you what to look for, not what to do everywhere. They build on Java interoperability (mapped types), inline functions, sequences and value classes.

From source to bytecode

The Kotlin compiler turns your .kt files into .class files. The JVM then runs them with an interpreter first and a just-in-time (JIT) compiler for the hot parts, which turns the bytecode into machine code at run time:

flowchart LR
    A["Main.kt"] --> B["kotlinc"]
    B --> C["MainKt.class (bytecode)"]
    C --> D["JVM interpreter"]
    D -->|"hot code"| E["JIT compiler"]
    E --> F["machine code"]

Kotlin compiles to bytecode; the JVM's JIT compiler optimizes the hot parts while the program runs.

Two facts follow from this. First, a short program that runs for milliseconds is dominated by JVM startup and an unoptimized warm-up phase, so a microbenchmark written with a plain loop and a stopwatch says very little. Second, the JIT removes many costs that look expensive in the source (it can inline small functions and sometimes avoid allocations), so intuition about "this must be slow" is often wrong.

Boxing: Int, Int? and List

The JVM has primitive types (int, long, double) that live directly in variables and arrays, and wrapper classes (java.lang.Integer and others) that are objects on the heap. Kotlin hides the difference, but the compiler chooses:

  • Int as a local variable, a parameter or a return type becomes a primitive int. This is fast.
  • Int?, List<Int>, Map<String, Int> and any generic type need objects, so each number is a boxed Integer. Boxing allocates (small values from -128 to 127 are cached) and uses more memory.
  • IntArray, LongArray, DoubleArray and the other specialized arrays store primitives side by side in memory.
Kotlin Which types are boxed?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last three lines show why you compare numbers with == in Kotlin and never with === (see equality and identity). They also show that every Int in a generic collection can be a separate object. For a list with a million numbers that is a million objects plus a million references, compared with one block of four megabytes for an IntArray.

What to do with this knowledge:

  • Use IntArray, LongArray and DoubleArray in numeric hot paths (see arrays).
  • Avoid Int? in tight loops; use a sentinel value or a separate boolean when profiling shows the boxing matters.
  • Use sumOf, sum, maxOrNull and similar built-ins, which are written for primitives where possible.
  • Do not convert everything to arrays "just in case". For a list of a few hundred items, nothing matters.

Lambdas and inline functions

A lambda passed to a normal function becomes an object (or an invokedynamic call on modern JVMs), and the function calls it through an interface. Closures that capture variables allocate a new object for each call. An inline function avoids this: the compiler copies the function body and the lambda body into the call site, so no function object exists. That is why the standard-library functions let, run, apply, also, forEach, map, filter and use (on collections and arrays) are all inline.

Kotlin What inline allows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The non-local return in the first function only compiles because forEach is inline. The mechanism has a price: inlining a big function into many call sites grows the bytecode. Rules of thumb: make small functions that take lambdas inline; do not inline large functions, or functions that take no lambda (the compiler warns about that); and use noinline and crossinline when a lambda must be stored or passed on (see inline functions).

Chains of operations: lists vs sequences

Every step in a chain on a List (map, filter, sortedBy) creates a new list with all the elements. A Sequence processes one element at a time through the whole chain, creates no intermediate lists and can stop early. The effect is clearly visible if you count how many times each stage runs:

Kotlin Counting the work done by a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The list version performs 20 steps and builds two intermediate lists. The sequence version stops after the first match and performs only 6. Sequences are not always better: for small collections and one or two steps, a plain list is faster and simpler, because a sequence adds a small object per stage. Use a sequence for large inputs, long chains, or when you only need the first few results.

Other common allocations to watch:

  • String concatenation in a loop. s += x creates a new string every time; use buildString or a StringBuilder (see strings).
  • Ranges. for (i in 0 until n) and for (i in 0..n step 2) compile to simple loops without a range object. A range stored in a variable and iterated later may allocate.
  • Default arguments and vararg. A vararg call creates an array each time.
  • Regex. Creating a Regex inside a loop recompiles the pattern every time. Create it once as a val.

Value classes and const

A value class wraps one value in a type that has no cost at run time in most cases. UserId and OrderId are different types for the compiler, but both are a single int in the bytecode, so you get type safety without an object:

Kotlin
// read-only example
@JvmInline
value class UserId(val value: Int)

fun load(id: UserId): String = "user-${id.value}"
// In bytecode the function takes an int. Its name gets a mangled suffix, like load-ABC123,
// so that load(UserId) and load(OrderId) cannot clash.

A value class is boxed again when it is used as a generic type argument or as a nullable type (UserId?, List<UserId>), so the same rule as for Int applies. A top-level const val is inlined as a literal wherever it is used, and object members and companion object members are accessed through a static field. Properties with default getters are direct field reads after JIT compilation, so you do not have to avoid properties for speed.

Reading the bytecode

When you want to know what the compiler produced, look at it. IntelliJ IDEA has a built-in view under Tools > Kotlin > Show Kotlin Bytecode, with a Decompile button that shows equivalent Java code. From the command line, the JDK includes javap:

Terminal
# read-only example
kotlinc Main.kt -d out
javap -c -p -cp out MainKt
TEXT
// read-only example: roughly what javap prints for  fun add(a: Int, b: Int) = a + b
public static final int add(int, int);
  Code:
     0: iload_0
     1: iload_1
     2: iadd
     3: ireturn

Decompiled code is a learning tool, not a goal. It shows you boxing (Integer.valueOf calls), hidden objects (lambda classes, Ref$IntRef for captured vars) and the code the compiler generated for data classes, when and coroutines (a state machine class per suspend function). Looking at it once teaches you more than any rule list.

Measuring: JMH and profilers

A trustworthy measurement needs three things: warm-up so that the JIT has finished compiling, many repetitions, and protection against the optimizer removing code whose result is never used. A stopwatch around a single loop in main provides none of them. The standard tool on the JVM is JMH (Java Microbenchmark Harness), and the kotlinx-benchmark library wraps it for Kotlin:

Kotlin
// read-only example: needs the kotlinx-benchmark Gradle plugin
@State(Scope.Benchmark)
open class SumBenchmark {
    private val array = IntArray(1_000_000) { it }
    private val list = array.toList()

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

    @Benchmark
    fun sumList(): Int = list.sum()     // returns the value, so the JIT cannot delete the work
}

Benchmarks answer "is A faster than B on this machine for this input". For a real application, start with a profiler (IntelliJ's built-in profiler, Java Flight Recorder, async-profiler) to find where time and allocation actually go. Optimize only what the profile shows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is stored as a primitive int on the JVM?

    A non-null Int as a local variable, parameter or return type is a primitive. Nullable and generic uses need the Integer wrapper object.
  2. 2. Why can you write return inside the lambda of forEach to leave the surrounding function?

    Inline functions copy the lambda into the call site, which makes a non-local return possible.
  3. 3. When is a Sequence a good choice over a List chain?

    Sequences avoid intermediate collections and can stop early. For tiny collections they add overhead without benefit.
  4. 4. What is the main problem with timing a single loop in main with System.nanoTime()?

    Without warm-up, repetition and a consumed result, the numbers mostly measure the JVM starting up. JMH handles these problems.

Summary

  • Kotlin and Java compile to the same kind of bytecode; most performance questions are about algorithms and I/O, not the language.
  • Int becomes a primitive only for non-null locals, parameters and returns; Int? and List<Int> are boxed, and IntArray stores primitives compactly.
  • Compare numbers with ==; boxed identity (===) is unreliable.
  • inline removes lambda objects and allows non-local return, but grows the code; use it for small functions that take lambdas.
  • Chains on lists create intermediate lists; sequences process element by element and can stop early.
  • Value classes give type safety with no extra object until they are boxed.
  • Read bytecode with IntelliJ's Show Kotlin Bytecode or javap; measure with JMH or a profiler, never with a plain stopwatch.

Next: Secure Kotlin Code