Allocation
- Kotlin course
- Expert
- Lesson 38/47
- 5 min
Learn object allocation and GC impact.
Allocation and GC
Allocation is the act of placing a new object on the JVM heap. Every allocation brings the garbage collector (GC) closer to a run; GC pauses can slow an app.
For example List(n) { it } allocates n boxed Integer objects. Using IntArray(n) instead keeps unboxed primitives and lowers allocation. You avoid creating objects in tight loops and reuse them. The allocInfo model in this lesson shows the concept.
Reducing allocation
Ways to reduce allocation: use primitive arrays, pool objects and avoid unnecessary intermediate collections.
For example Array<Int> creates 100 boxed objects while IntArray(100) does not. StringBuilder avoids creating a new String on every concatenation. Sequence removes intermediate lists. These small changes make a big difference in hot loops.
Practice Write allocInfo
Define fun allocInfo(): String. It should return "Allocation". In main, write println(allocInfo()).
Starter code
// add the allocInfo function
fun main() {
// print the allocation info
}Sample solution
fun allocInfo(): String = "Allocation"
fun main() {
println(allocInfo())
}Expected output
Allocation
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the alloc body
fun alloc(n: Int): List<Int> = List(n) { ____ }
fun alloc(n: Int): List<Int> = List(n) { it }
Explanation: List(n) { it } allocates an object per index.
2 Match the allocation parts
| Term | Meaning |
|---|---|
allocation |
Heap allocation |
GC |
Garbage collector |
IntArray |
Unboxed array |
StringBuilder |
String concat |
3 Which reduces allocation?
A primitive array allocates fewer objects.- A new List every loop
- String concatenation
- Creating a data class
- IntArray (instead of boxed Array) Correct answer
Explanation: IntArray holds unboxed primitives; allocation drops.