Examples · Kotlin

Benchmark Kotlin code, warmed up

Timing code with System.nanoTime() around a single call mostly measures the JIT warming up. Util.benchmark runs each block until it is warmed up, then times it in batches and reports the mean with its margin of error.

Here three ways of sorting 10,000 numbers are compared. The table shows the mean and median time per call, calls per second, memory allocated per call, and how each compares with the fastest.

The query

kotlin-benchmark.kts · paste it into a Kotlin tab and press F5, or run byterunner run kotlin-benchmark.kts in a terminal

// Which is faster? Each block is warmed up first, so the JIT has compiled it, then timed in batches.
val numbers = (1..10_000).shuffled(kotlin.random.Random(42))

Util.benchmark("sorted()") { numbers.sorted() }
Util.benchmark("sortedBy { it }") { numbers.sortedBy { it } }
Util.benchmark("toIntArray().sort()") { numbers.toIntArray().also { it.sort() } }

What it shows

The output of that run, from byterunner run. In the app each table is a sortable grid.

Benchmark
Code                 Mean     ± 95%      Median   Min        Calls/sec  Allocated/call  First call  Calls  vs fastest
-------------------  -------  ---------  -------  ---------  ---------  --------------  ----------  -----  ------------
sorted()             6.21 ms  1.03 ms    5.54 ms  3.49 ms    161        90.0 KB         12.19 ms    320    4.05× slower
sortedBy { it }      4.01 ms  390.63 µs  3.64 ms  3.08 ms    249        3.2 MB          20.27 ms    460    2.61× slower
toIntArray().sort()  1.53 ms  263.67 µs  1.47 ms  914.37 µs  652        39.1 KB         7.92 ms     1,395  fastest
(3 rows)

These numbers came from one run on one machine; yours will differ, but the order rarely does. Boxing shows up here: sorting an IntArray allocates far less than sorting a List<Int>.

In the app, select a line and press Alt+Shift+B to benchmark it without writing Util.benchmark yourself. The same works in Java and Groovy queries.

Download ByteRunner Free for Windows and Linux. Getting started

More examples