Junior — Middle
What is the acceptable size of an inline function in code for optimal compilation and readability?
sobes.tech AI
Answer from AI
The optimal size of an inline function depends on balancing code readability and compilation efficiency. Generally, inline functions should be short — usually a few lines (up to 5-10 lines), to:
- Improve performance by eliminating function call overhead (especially for small, frequently called functions).
- Not impair code readability and maintainability.
If a function is too large, the compiler may ignore the inline suggestion, and the code can become harder to understand. Therefore, inline is best used for simple getters, setters, and small utility functions.
Example in Kotlin for Android:
inline fun <T> measureTime(block: () -> T): T {
val start = System.nanoTime()
val result = block()
val end = System.nanoTime()
println("Time: ${end - start} ns")
return result
}
Here, the function is short and benefits from inlining.