Andrey Minogin

Reliability and Performance of LLM, JVM and Postgres systems

Garbage costs when you create it

Blue sparks of short-lived garbage fade along a line of execution while a few orange blocks are lifted into a kept pile

Did you know that freeing memory in Java costs nothing, but creating an object takes three steps, and two of them are expensive? Let’s look closer, taking a simple string comparison as an example.

Optimizing the graph

We continue the optimization of the Maven Central graph. We resolve the classpaths of every Apache project on Maven Central, 92,667 classpaths, in memory, on a laptop. We find what to optimize, and precisely measure every step, with TickSnick, a profiler I wrote.

The program walks the dependency graph. When it meets the same library twice (org.slf4j:slf4j-api at 1.7.36 and at 2.0.0-beta1), it calls merge, which compares two version strings and keeps the higher one. After three optimization steps, what is the slowest thing left? Let’s ask TickSnick.

Its report, each operation’s own time, the top rows:

Plaintext
Op          | Thread-time% |       Calls | Thread-time per call
------------+--------------+-------------+---------------------
merge       |        37.3% | 199,138,728 |                240ns   // compare two versions
passedOn    |        11.5% | 222,178,167 |               66.3ns   // pick the edges to follow
visit       |        5.03% | 562,928,865 |               11.5ns   // mark a release as seen
...

merge is on top, far ahead of the walk’s other steps: 37% of all the time, 199 million calls, 240 ns each. That is our target.

The code anyone writes

The comparison splits each version into parts (2.0.0-beta1 into 2, 0, 0, beta, 1) and compares the parts one by one. I wrote the splitting the obvious way:

Kotlin
private fun parts(version: String): List<String> {
    val parts = ArrayList<String>()
    val part = StringBuilder()
    for (c in version) {
        if (c in SEPARATORS) {
            if (part.isNotEmpty()) parts.add(part.toString())
            part.clear()
            continue
        }
        if (part.isNotEmpty() && isDigit(part.last()) != isDigit(c)) {
            parts.add(part.toString())
            part.clear()
        }
        part.append(c)
    }
    if (part.isNotEmpty()) parts.add(part.toString())
    return parts
}

Looks innocent. But every call creates a list, a StringBuilder and a new String for every part, several hundred bytes in all. How much garbage is that in total? TickSnick can tell us: it counts the bytes each operation allocates, exactly, not by sampling, adding about 0.1% to the wall time or less. Here is its report:

Plaintext
Op               |   Wall | Allocated
-----------------+--------+----------
runBatch         |  25.0s |    109 GB   // three batches
  select         |  18.0s |   88.9 GB   // pick the highest versions
    - merge      |  12.0s |             // compare two versions
    - passedOn   |  1.65s |             // pick the edges to follow
  via            |  4.08s |   6.31 GB   // who brings each library
  reach          |  1.50s |   2.22 GB   // collect the classpath

select, the first of the program’s three walks, allocates 88.9 of the 109 GB. Inside select, two operations create objects: the comparison and the edge filter. The filter allocates about 4 GB. So the comparison allocates about 85 GB: 78% of all the garbage.

So before we touch a single line, TickSnick already tells us what to expect: if the comparison stops creating objects, about 78% of the garbage should go away.

Same logic, no garbage — 2.7x faster, and not because of the GC

Let’s rewrite the comparison so that it never cuts a version into new strings. Instead of a list of parts, it keeps two ints per part: where the part starts and ends in the original string. It follows the same rules and gives the same answers; we check it on 815,000 real pairs. But it creates no objects at all.

Now let’s run both versions and open TickSnick’s diff:

Plaintext
Op           |                      Wall |                 Allocated
-------------+---------------------------+--------------------------
runBatch     | 25.0s -> 16.0s       -36% |  109 GB -> 24.6 GB   -78%
  select     | 18.0s -> 8.79s       -51% | 88.9 GB -> 4.14 GB   -95%
    - merge  | 12.0s -> 4.44s       -63% |
  via        | 4.08s -> 4.24s          ? | 6.31 GB -> 6.32 GB  +0.1%
  reach      | 1.50s -> 1.34s -1.2..-20% | 2.22 GB -> 2.22 GB      =

Look at the Allocated column: -78%. Exactly what TickSnick predicted before we changed a line! What select still allocates, 4.14 GB, is the edge filter alone, as estimated. The other two walks, via and reach, allocate the same as before. (In the Wall column, a ? or a range like -1.2..-20% means four runs are not enough to pin the change down.)

And the speed? merge goes from 240 to 88.8 ns a call: 2.7x faster. The batches get 36% faster.

Wait, maybe it is just the GC working less? TickSnick samples a thread’s time only while the program runs, never during a GC pause; the pauses get a column of their own. So 240 and 88.8 ns contain no GC at all: the thread itself gets 2.7x faster.

What exactly gets faster

But hold on: the new code does one more thing. It stops at the first part that differs, while the old code splits both versions whole. So which change gives the speed-up? Let’s write a third version to find out. It does all the old work, splitting everything and copying every character, but into buffers it reuses, so it creates no objects. On one thread, a compare takes:

Where the 2.7x comes from: old code 320 ns, the same work without objects 200 ns, new code 121 ns per compare

So the objects alone cost 120 ns: 60% of the 200 ns we save. And no GC runs during this test: we pay for the objects while we create them.

Why so expensive? Creating an object takes three steps, and only the first is cheap:

  1. Taking the space: the JVM bumps a pointer. A few instructions.
  2. Filling it: the thread writes the header, the fields and the contents, about 582 bytes per compare here.
  3. Cold memory: a new object lands on memory the CPU has not touched lately, so the CPU first has to fetch it from RAM.

Our third version writes into the same few buffers, and they stay in the cache. That is the usual explanation; we have not measured it.

The GC barely noticed

Now the GC. The garbage is 4.4x smaller, so the pauses should be too, right? TickSnick’s Paused column: 3.57 s -> 2.28 s. Only 1.6x. Why?

Java’s default collector, G1, puts new objects into an area of the heap called eden. When eden fills up, G1 stops the program, copies the live objects out and marks eden empty. It never touches the dead ones, so freeing them costs nothing. New objects simply overwrite them later, and that write is the cost we met above.

So a pause pays for what it copies, not for the garbage. The GC log agrees: about 180 ms per GB copied, whatever the amount of garbage.

Pause time against GB copied: the pauses lie on one straight line. Against GB of garbage freed: no relation

Why the pauses fall at all

The answer is not obvious. It is about what the program keeps: its results, the dependency lists it resolves, about 3.3 GB a batch.

G1 has two places for objects that are still in use: a small waiting area, about 0.5 to 1 GB here, and a big area for long-lived objects.

With lots of garbage, eden fills up every second or so, and each pause finds only a small pile of new results, about a gigabyte or less. That fits into the waiting area, so G1 copies it there. At the next pause those results are still in use, and G1 copies them again, into the long-lived area. Copied twice.

With little garbage, eden fills up slowly, and by the first pause the pile of new results has grown to 1.7 to 2.8 GB. That is too big for the waiting area. G1 fills it and copies the rest straight into the long-lived area, once. In all, G1 copies 13.2 GB instead of 21.2 GB, and the pauses shrink with it.

Less garbage overall, but bigger piles to keep.

One batch on a timeline: the old code pauses 7 times for 1.21 s, the new code 2 times for 0.79 s

Less garbage can’t take us much further. Every kept byte must be copied at least once: 10 GB kept at about 0.18 s per GB is about 1.8 s of pauses, and we are already at 2.3 s. And there is a catch: rarer pauses are longer pauses. The longest one grows from 310 to 500 ms: it has a bigger pile to copy.

What to take away

If hot code creates temporary objects, do not look for their cost in the GC log. The cost is in your own thread, at the moment it creates the objects. The GC pays for what you keep, not for what you throw away.

TickSnick shows both halves of this: where the garbage is created, and that the speed-up belongs to the thread, not to the GC.


Have a problem like this in your own system? I start with two sessions on it — €2,000 fixed. How it works →

Andrey Minogin — software architect, 15+ years on data-intensive systems. I find out why a system in production is slow, expensive or wrong — in Java and Kotlin services, PostgreSQL and LLM workflows.

When the head of one of the world’s top PostgreSQL consultancies reviewed database work I had done, his conclusion after a day on site: there was nothing he could add.

Work with me · LinkedIn · andrey@minogin.com