inline Functions: Eliminating Lambda Overhead
Mark functions as inline to avoid object creation for lambda parameters.
What Is an inline Function?
Normally, a lambda passed to a function is compiled into an anonymous class. Each invocation allocates a new object, which costs memory and time. The inline keyword tells the compiler to copy the function body (and its lambda arguments) directly into the call site.
Declaring inline
Add the inline modifier before fun:
inline fun measureTime(block: () -> Unit): Long {
val start = System.nanoTime()
block()
return System.nanoTime() - start
}All lessons in this course
- inline Functions: Eliminating Lambda Overhead
- noinline and crossinline Modifiers
- reified Type Parameters: Accessing T at Runtime
- Practical Reified Patterns: Parsing, DI & Serialization