0
0
Kotlinprogramming~5 mins

Inline functions and performance in Kotlin

Choose your learning style9 modes available
Introduction

Inline functions help your program run faster by reducing extra steps when calling small functions.

When you have small functions that are called many times.
When you want to avoid the cost of creating extra objects for function calls.
When you use lambda expressions and want to improve speed.
When you want to keep your code clean but still fast.
When you want to reduce memory use caused by function calls.
Syntax
Kotlin
inline fun functionName(parameters) {
    // function body
}

The inline keyword tells Kotlin to copy the function code directly where it is called.

This avoids the usual function call overhead.

Examples
A simple inline function that prints a greeting.
Kotlin
inline fun greet(name: String) {
    println("Hello, $name!")
}
An inline function that takes another function as a parameter to perform an operation.
Kotlin
inline fun operate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}
Sample Program

This program uses an inline function measureTime to measure how long a block of code takes to run. The block sums numbers from 1 to 1,000,000.

Kotlin
inline fun measureTime(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    val end = System.currentTimeMillis()
    println("Time taken: ${end - start} ms")
}

fun main() {
    measureTime {
        var sum = 0L
        for (i in 1..1_000_000) {
            sum += i
        }
        println("Sum: $sum")
    }
}
OutputSuccess
Important Notes

Inline functions are best for small functions to avoid code size increase.

Using inline with large functions can make your program bigger.

Inline functions improve performance especially when using lambdas.

Summary

Inline functions copy code to where they are called to run faster.

They reduce the overhead of function calls and lambda objects.

Use them for small, frequently called functions to improve speed.