High-order functions are very useful and fancy, but they come with a caveat—performance penalties. Remember, from Chapter 2, Getting Started with Functional Programming, in the section, First-class and high-order functions, that on compilation time, a lambda gets translated into an object that is allocated, and we are calling its invoke
operator; those operations consume CPU power and memory, regardless of how small they are.
A function like this:
fun <T> time(body: () -> T): Pair<T, Long> { val startTime = System.nanoTime() val v = body() val endTime = System.nanoTime() return v to endTime - startTime } fun main(args: Array<String>) { val (_,time) = time { Thread.sleep(1000) } println("time = $time") }
Once compiled, it will look like this:
val (_, time) = time(object : Function0<Unit> { override fun invoke() { Thread.sleep(1000) } })
If performance is a priority for you (mission critical application, games, video streaming...