Part 8 · 1 chapters · ~8 min
Performance
Kotlin and Java bytecode parity, inline functions and lambdas, boxing with nullable primitives and generics, sequences versus collections, value classes, coroutine dispatcher choices and thread starvation, JMH through kotlinx-benchmark, async-profiler flame graphs, startup and GraalVM native images, and JVM tuning shared with the Java course.
9
Where Kotlin adds or removes cost
code
// intermediate lists: three allocations of 1M elements
val total = items.map { it.amountKobo }.filter { it > 0 }.sum()
// lazy sequence: one pass, no intermediate lists
val total2 = items.asSequence().map { it.amountKobo }.filter { it > 0 }.sum()
val boxed: List<Long> = … // each element a java.lang.Long object
val prim: LongArray = … // primitive array: no boxing in hot loops
@State(Scope.Benchmark) open class FeeBench { // kotlinx-benchmark (JMH)
@Benchmark fun fees(): Long = transfers.sumOf { fee(it.amountKobo, it.channel) }
}KOTLIN PERFORMANCE
mostly the JVM's story, plus a few Kotlin-specific costs
swipe the figure sideways, or tap expand for full screen
1/4
the JVM
Performance is mostly the JVM's: the same JIT, GCs and profiling tools as Java (Java course P9).
JVM performancesame tools