Junior — Middle
What are the differences between a standard function and a function embedded in code for efficiency improvement?
sobes.tech AI
Answer from AI
A standard function is a regular function defined separately and called by name. An inline function, embedded directly in the code, is typically used to improve efficiency by eliminating the overhead of a function call.
Main differences:
- Standard function: calling it involves jumping to the function's address, which takes time for stack operations.
- Inline function: the compiler inserts the function's body directly at the call site, reducing overhead and potentially improving performance.
Example in Kotlin (Android):
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
val end = System.currentTimeMillis()
println("Execution time: ${end - start} ms")
}
// Usage
measureTime {
// code whose execution time needs to be measured
}
Thus, inline functions are useful for small, frequently called functions, especially with lambdas, to avoid creating additional objects and calls.