Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
226: Inline Function Bytecode Generation
By now, you know that the inline keyword is usually recommended for higher-order functions to avoid the performance hit of creating function objects. But "performance hit" is a vague term. To really understand why inline matters, we need to stop looking at the Kotlin source and start looking at what the compiler is actually handing to the JVM.
Writing a simple execution timer
I want to build a quick utility that measures how long a block of code takes to run. It's a classic use case for a higher-order function. I'll start with a standard implementation without any inlining.
fun <T> measureTime(block: () -> T): T {
val start = System.currentTimeMillis()
val result = block()
val end = System.currentTimeMillis()
println("Execution time: ${end - start}ms")
return result
}
Now, let's use it in a main function to simulate some work:
fun main() {
measureTime {
Thread.sleep(100)
println("Work done!")
}
}
Peeking at the Function object overhead
If you open the "Show Kotlin Bytecode" tool in IntelliJ and then "Decompile" it back to Java, you'll see something interesting. You won't see the measureTime logic pasted inside main. Instead, you'll see that the compiler created an anonymous class that implements Function0.
In the decompiled Java, the call to measureTime looks roughly like this:
measureTime(new Function() {
public Object invoke() {
Thread.sleep(100);
System.out.println("Work done!");
return Unit.INSTANCE;
}
});
Every time main calls measureTime, a new object is instantiated on the heap. For a one-off call, it's irrelevant. But if this were inside a tight loop in a game engine or a high-frequency trading app, those allocations would trigger the Garbage Collector far more often than necessary.
Removing the middleman with the inline keyword
Now, I'll add the inline modifier to measureTime. This tells the compiler: "Don't pass this lambda as an object; just copy the code of the lambda directly into the call site."
inline fun <T> measureTime(block: () -> T): T {
val start = System.currentTimeMillis()
val result = block()
val end = System.currentTimeMillis()
println("Execution time: ${end - start}ms")
return result
}
When I check the bytecode again, the anonymous Function class is gone. The decompiled main now looks like this:
long start = System.currentTimeMillis();
Thread.sleep(100);
System.out.println("Work done!");
long end = System.currentTimeMillis();
System.out.println("Execution time: " + (end - start) + "ms");
The logic of measureTime and the logic of the lambda have been fused into a single stream of instructions. No object allocation, no invoke() method call. Just raw execution.
The binary bloat trap
Early in my career, I thought, "If this is faster, why not inline everything?" I once tried to inline a massive validation function that was 50 lines long and called in 20 different places across a project. I felt clever until the build size spiked and the instruction cache on the CPU started missing.
I made the mistake of ignoring the "copy-paste" nature of inlining. If you inline a large function, you aren't just saving an object allocation; you are duplicating that entire block of bytecode everywhere it's used. I had to revert those changes and leave the large functions as standard calls. The rule of thumb I use now: inline small, higher-order functions that take lambdas. If the function is large and doesn't take a lambda, inline provides almost no benefit and only risks bloating your binary.
📋 Practical Task
Build a Bytecode-Optimized Resource Wrapper
Create a higher-order function called executeWithLock that simulates a resource lock. The function should take a Lock` object and a lambda block: () -> T. It should call lock.lock(), execute the block, and ensure lock.unlock() is called in a finally block.
Requirements:
- The function must be marked as
inlineto ensure that no function object is created for the execution block. - Create a simple
Lockclass withlock()andunlock()methods that print their status to the console. - In your
mainfunction, useexecuteWithLockto print a message. - Verify your work by using the "Show Kotlin Bytecode" -> "Decompile" feature in your IDE. Confirm that the
Lockcalls and the print statement appear sequentially in themainmethod, without anyFunctionobject instantiation.
There are no comments for now.