1. Introduction
If you are writing a learning project and it processes 10 lines, then memory questions sound like nitpicking at the level of “don’t breathe near the CPU — it’ll overheat.” But as soon as there is more data (logs, files, records in collections, reports), it suddenly turns out that the most expensive problems are not “complex algorithms,” but a bunch of small allocations and constant cleanup by the garbage collector. On the JVM this shows up as unpredictable pauses, spikes in memory usage, and the feeling that the program either flies or stares thoughtfully out the window.
To speak the same language as the JVM, we need a working model in three words: stack, heap, GC. This model does not explain absolutely everything (today we are intentionally not diving into bytecode/JIT/fine GC tuning), but it explains 80% of “why it got slower” and “where the memory went.”
2. Minimal JVM memory model: stack and heap
When you call a function in Kotlin, you don’t just “jump to another line.” The JVM needs to store somewhere what this call is, which local variables it has, and where to return. That place is the stack. And when you create objects (classes, strings, lists, exceptions), they usually live in the heap. And when you stop referencing them, GC (the garbage collector) appears, periodically showing up and saying, “Alright, who’s unnecessary here?”
One important thought right away: most performance problems in “typical application Kotlin” are not about the stack, but about the heap. The stack usually fails dramatically (for example, StackOverflowError), while the heap fails slowly and sadly: “something keeps eating more memory and the pauses are kind of weird.”
Stack: memory for function calls and why it’s “not infinite”
Imagine a stack of trays in a cafeteria. You put a new tray on top when you call a function, and remove it when the function ends. While the function is running, its “tray” holds the local variables (roughly speaking). That’s the stack: a LIFO structure (last in — first out).
For us, the practical meaning is this: if you accidentally do infinite recursion or very deep recursion, the stack grows, grows, grows… and then runs out. In the JVM this usually leads to StackOverflowError (in Kotlin it is also considered a serious Error, not an “ordinary error you should catch”). Kotlin’s exception documentation explicitly emphasizes that such things are problems from which an application often cannot “recover normally.”
We don’t need to optimize the stack right now. What matters is understanding: the stack is about call depth and per-call local data, not about “all your lists and strings.”
Heap: memory for objects — everything interesting and everything expensive
The heap is a “shared warehouse of objects.” Almost everything in Kotlin that looks like an object ends up there: class instances, String, collections, Pair, lambdas (in some cases), exceptions, and so on.
The key point: the heap “lives longer than a single function call.” You created a MutableList, returned it from a function — it continues to exist. As long as there are references, it is considered needed. As soon as there are no references, the object becomes a candidate for garbage collection.
And this is where a subtle but very practical thought appears: performance is strongly affected not only by “how many objects are alive,” but also by “how often you create new ones”. If you create a million tiny objects every second, the GC will be very busy.
References: why val doesn’t “put the object into a variable”
Many beginners subconsciously think that val x = ... “puts an object into a variable.” On the JVM it is often more useful to think like this: a variable stores a reference to an object in the heap (an address/pointer in everyday terms), not the object itself.
That’s why the phrase “a collection in val is immutable” is incorrect (if it is a MutableList). val protects the reference (you can’t reassign a different collection), but it does not forbid mutating the object itself. Kotlin documentation explicitly notes that you can keep even a mutable collection in a val to avoid losing control of the reference and accidentally swapping it for another collection.
A mini example to “feel” the idea of references:
fun main() {
val xs = mutableListOf(1, 2)
val ys = xs
ys.add(3)
println(xs) // [1, 2, 3]
println(ys) // [1, 2, 3]
}
ys didn’t “copy the list”; it got a second reference to the same object in the heap.
3. GC: who takes out the trash and why it sometimes gets in the way
The garbage collector in the JVM is a mechanism that frees heap memory when objects become unreachable (no one references them anymore). It does what, in languages without GC, you would have to do manually (and yes, doing it manually ends either with leaks, or with “oops, we freed memory twice,” or with all of the above).
But we pay for convenience with the fact that garbage collection is work that consumes resources and sometimes leads to pauses. In the best case you don’t notice GC at all. In the worst case the program starts to “stutter,” and you open monitoring and see: the CPU isn’t doing useful work, but the app keeps pausing.
A useful everyday model: the GC is happier the less garbage you produce. And here we smoothly come to allocations.
Let’s draw a simplified diagram of an object’s “life path”:
flowchart TD
A[Created an object in heap] --> B[There are references to it]
B --> C{Did references disappear?}
C -- no --> B
C -- yes --> D[The object becomes a candidate for GC]
D --> E[GC frees the memory]
This is enough to understand further why “extra temporary objects” are not a harmless little detail.
4. Allocations: where Kotlin creates extra objects
An allocation is the moment when the JVM reserves space in the heap for a new object. One allocation by itself is usually not a catastrophe. The catastrophe is a thousand allocations in a loop that runs a million times. So our goal is to learn to spot typical places where Kotlin code “accidentally” creates lots of temporary objects.
The most honest way to think is: anything that looks like “created a new value” potentially creates a new object. Sometimes the compiler optimizes; sometimes it doesn’t. So we keep in mind simple patterns that almost always come with a cost.
Strings and concatenation in loops: the classic garbage factory
Strings in the JVM are objects. Moreover, they are immutable: if you did "a" + "b", the JVM didn’t “append to the old string” — it created a new one.
In Kotlin the + operator for strings is convenient, but if you start doing result += ... in a loop, you often create many temporary strings. A typical anti-example:
fun buildReportBad(lines: List<String>): String {
var s = ""
for (line in lines) {
s += line + "\n"
}
return s
}
Yes, it’s readable. Yes, it works. Yes, GC cries afterward.
The right everyday tool is StringBuilder:
fun buildReportGood(lines: List<String>): String {
val sb = StringBuilder()
for (line in lines) {
sb.append(line).append('\n')
}
return sb.toString()
}
StringBuilder keeps an internal buffer and grows it as needed, so you don’t create a string at every step.
Collections and map/filter chains: intermediate lists are allocations too
Many collection operations in Kotlin return a new collection: map, filter, sorted, etc. This is great for readability and functional style, but it’s important to remember: each such operation may create an intermediate list.
If you have a chain of five transformations on a large collection, you potentially create several large temporary lists. Sometimes that’s fine (readability is simply more important). Sometimes it’s expensive. This is where we recall Sequence: it allows you to make transformations lazy and reduce the number of intermediate collections (but it’s not free either).
By the way, Kotlin documentation emphasizes the difference between collections and arrays: an array has a fixed size, while collections are more convenient for adding/removing elements and for typical tasks overall. This is not directly about memory, but it matters indirectly: attempts to “optimize everything with arrays” often turn into complex and fragile code.
Pair, Triple, and small temporary objects: seems small, but it adds up fast
Pair and Triple are convenient, but they are objects too. If you use them as temporary containers in a hot spot (for example, returning a Pair from a function in a loop), you create many short-lived objects.
Sometimes that’s okay. Sometimes it’s better to return separate values differently (for example, via a specialized model, or via updating an accumulator, or via fold). But it’s important not to turn the code into “optimization for optimization’s sake”: first you must understand what exactly is your hot path.
5. Boxing: why List<Int> can be heavier than it seems
Boxing is the situation where a “simple number” (Int) turns into a wrapper object because it needs to be placed where objects are expected (for example, into a generic collection).
On Kotlin/JVM, generics mostly work with reference types, and therefore List<Int> at the JVM level often stores not “bare ints,” but wrapper objects. This does not mean List<Int> is always evil. It means that for huge arrays of numbers it can sometimes be beneficial to use specialized structures.
Kotlin documentation about arrays explicitly says that if you use Array with primitives, they will be boxed, and suggests using primitive arrays (IntArray, DoubleArray, etc.) instead to avoid the overhead of boxing.
Array<Int> vs IntArray: a small “on your fingers” example
fun main() {
val a: Array<Int> = arrayOf(1, 2, 3)
val b: IntArray = intArrayOf(1, 2, 3)
println(a.joinToString()) // 1, 2, 3
println(b.joinToString()) // 1, 2, 3
}
From the outside it’s almost the same. But the idea is: IntArray stores primitives more tightly and without boxing.
When this matters in our “practical CLI project”
In our learning application (a hypothetical CLI tracker/analyzer where we store records and build reports), most data is objects: expense/event/string records. Here, boxing is not the main enemy.
But if you add a subsystem that stores large numeric series (for example, daily sums, metrics, time series), then switching from List<Int> to IntArray can sometimes sharply reduce memory pressure. And that affects the GC: fewer objects — less garbage — fewer pauses.
6. Overheads: exceptions and reflection
In previous days of the course, we already discussed exceptions as an error-handling mechanism. Here we look at them from the perspective of memory and performance — and we put reflection next to them because it has a similar profile: “powerful, but not free.”
Exceptions and stack traces: why try/catch for parsing is expensive
An exception is an object. And it carries context: a message, a cause (cause), and the “most expensive” part — the stack trace, i.e., a list of stack frames showing how execution arrived at the point of failure. Kotlin documentation explains separately that a stack trace is a sequence of function calls and gives an example of JVM output.
This is useful for debugging, but it means: creating an exception is not the same as “returned null”. An exception is usually more expensive because it needs to collect diagnostic information.
Moreover, the documentation emphasizes that exceptions are stateful objects, and you shouldn’t make them singleton objects, because the state (including the stack trace) should reflect the place where it occurred. This is another hint: an exception is not a “cheap flag,” but a “thick folder of documents.”
If the error is expected (for example, the user entered something that is not a number), it is often better to use toIntOrNull()/toDoubleOrNull() and validation. In our course this was already covered: “read → prepare → parse,” and if there’s a problem — return null and ask to repeat the input.
And here it’s convenient to recall the fail-fast style: require and check are a quick way to throw an exception if you cannot proceed, and Kotlin officially describes these preconditions as a way to automatically throw exceptions when conditions are violated.
Reflection and memory: why dynamic access is heavy
We just studied reflection, so now we can honestly say: yes, it’s powerful, but there is no such thing as free.
Reflection often leads to:
- additional metadata (and sometimes even an extra dependency),
- member lookup by scanning lists,
- creation of helper objects for invocation,
- more complex tracing and debugging.
From a memory perspective, the main practical advice is: don’t do reflection inside a hot loop. If you need to call a method/read a property by name, it’s usually worth finding a “descriptor” once (a conditional KFunction/KProperty) and reusing it, instead of rescanning memberFunctions every time.
Even if you don’t measure this with benchmarks (and we’re not diving into measurement discipline today), common sense works great here: repeating “scan a list” + “wrappers” + “invoke via call” 100000 times is almost always a bad idea.
7. Mini refactor: reduce allocations without losing readability
Now we’ll do the most useful thing for real life: look at a piece of code from the “practical CLI project” and improve it so it creates less garbage while remaining easy to understand. Important: our goal is not “squeeze the maximum,” but “don’t shoot yourself in the foot by default.”
Let’s assume we have a domain model (simplified):
data class Expense(
val title: String,
val amountCents: Int
)
And we build a text report from a list of expenses.
Bad report building via +=
fun renderExpensesBad(items: List<Expense>): String {
var s = "Expenses:\n"
for (e in items) {
s += "${e.title}: ${e.amountCents} cents\n"
}
return s
}
Does it work? Yes. Does it create lots of temporary strings? Also yes.
Good report building via StringBuilder
fun renderExpensesGood(items: List<Expense>): String {
val sb = StringBuilder()
sb.append("Expenses:\n")
for (e in items) {
sb.append(e.title)
.append(": ")
.append(e.amountCents)
.append(" cents\n")
}
return sb.toString()
}
This is still readable, but it creates fewer temporary objects. Also, we removed unnecessary interpolation in the string inside the loop.
Arrays vs collections in reports: choose the structure consciously
Sometimes students try to “speed everything up” by switching to arrays. But arrays have a fixed size, and add/remove operations there lead to creating a new array and copying elements (this is explicitly shown in Kotlin documentation as an inefficient path when changes are frequent).
Therefore, in our project the base container for records is a collection (MutableList, List). And that is correct. But if a specialized numeric buffer appears (for example, an IntArray for sums by category), then you can selectively use a primitive array to avoid boxing overhead.
8. Typical mistakes
Mistake #1: build large strings via += in a loop and then be surprised why it got sad “on big data.”
The problem is not that the + operator is bad. The problem is that a string is immutable, and with each += you often create a new string in the heap and leave the old one for the GC. On small data it’s unnoticeable; on large data it turns into a garbage factory.
Mistake #2: use exceptions as a regular branching mechanism (“if it didn’t work — we’ll catch it”).
An exception is a stateful object, including a stack trace, which is needed for diagnostics and debugging. The documentation shows that the stack trace reflects the call chain, and that information is not free. If an error is expected (for example, input parsing), it’s better to return null/Result/a sealed result and handle it calmly, leaving exceptions for truly exceptional situations.
Mistake #3: not understand where boxing happens and store huge numeric arrays in Array<Int> / List<Int> when you need a dense buffer.
Kotlin explicitly warns: using Array with primitives leads to boxing, and for such tasks there are primitive arrays (IntArray, DoubleArray, etc.). This doesn’t mean you should rewrite the whole project using arrays; it means that for “a million numbers” you should at least think about it.
Mistake #4: do reflection in a hot spot and repeat member lookup on every iteration.
Reflection is a tool that reduces compiler guarantees and adds overhead. If you must use it for dynamic behavior, try to limit the scope and cache lookup results so you don’t scan metadata again and again.
Mistake #5: try to optimize memory blindly, breaking readability where it isn’t needed.
The most painful situation is when code became three times more complex but only sped up by 0.5% in a place that wasn’t a bottleneck anyway. It’s far more useful to first eliminate obvious garbage factories (string concatenation in a loop, unnecessary intermediate collections, exceptions in a mass scenario), and only then think about subtler things.
GO TO FULL VERSION