Junior — Middle
What is the difference between inline functions and regular functions, and what are their advantages?
sobes.tech AI
Answer from AI
Inline functions are functions that the compiler tries to replace directly at the call site, rather than calling them as regular functions. This reduces the overhead of function calls (for example, jumping to an address and saving context).
Advantages of inline functions:
- Increased performance by eliminating the function call.
- The compiler can optimize the code better, for example, by removing unnecessary variables.
However, if a function is large, inline may increase the size of the binary, so the compiler might ignore inline for large functions.
Example in Kotlin:
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
println("Time: ${System.currentTimeMillis() - start} ms")
}
// Usage
measureTime {
// code whose execution time needs to be measured
}