Inline functions

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), you can mark a high-order function as inline:

inline fun <T> inTime(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 (_, inTime) = inTime { Thread.sleep(1000) }
println("inTime = $inTime")
}

Once compiled, it will look like this:

val startTime = System.nanoTime()
val v = Thread.sleep(1000)
val endTime = System.nanoTime()
val (_, inTime) = (v to endTime - startTime)

The whole function execution is replaced by the high-order function's body and the lambda's body. The inline functions are faster, albeit generating more bytecode:

2.3 milliseconds per execution doesn't look like a lot, but in the long run and with more optimizations, can create a noticeable compound effect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.104.27