Quick revision
The short answer
The array is created by the caller before log() even starts, so checking the level inside the method cannot avoid it. We add fixed-arity overloads, such as log(String), log(String, Object), log(String, Object, Object) and a three-argument version, as SLF4J and List.of do. Existing source picks the more specific overloads when it is recompiled, while old compiled callers keep linking to the unchanged varargs method, so nothing breaks. For expensive arguments we also offer a level check or a Supplier-based method, and we confirm the gain with JFR allocation profiles before and after.
What to remember
In this answer, we saw that a varargs logging call allocates its array at the call site, before the method can check the log level. Adding fixed-arity overloads for zero to three arguments removes that allocation for recompiled callers, while the unchanged varargs method keeps old binaries linking, so the change is both source and binary compatible. We checked that every call shape, including a trailing exception, behaves the same, used level checks or Supplier arguments for expensive values, and planned to confirm the improvement with JFR allocation profiles and a JMH benchmark with the GC profiler.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The array is created by the caller before log() even starts, so checking the level inside the method cannot avoid it. We add fixed-arity overloads, such as log(String), log(String, Object), log(String, Object, Object) and a three-argument version, as SLF4J and List.of do. Existing source picks the more specific overloads when it is recompiled, while old compiled callers keep linking to the unchanged varargs method, so nothing breaks. For expensive arguments we also offer a level check or a Supplier-based method, and we confirm the gain with JFR allocation profiles before and after.
Why this question is asked
Logging calls sit on almost every code path, so a small cost per call is multiplied by every request in the fleet. An array of two references is only about 24 bytes, but at a few hundred thousand debug calls per second per instance that is several megabytes of garbage per second, which means more frequent young collections and more CPU spent on GC. Interviewers ask this scenario because it combines a language detail, where varargs arrays are built, with API evolution under compatibility constraints. In this answer, we will see where the allocation happens and why the level check cannot help, add fixed-arity overloads, check why they are source and binary compatible, look at guards and suppliers for expensive arguments, and measure the result.
1Where the Array Is Created
A varargs parameter is an array, and the compiler builds it at the call site. A call such as log.debug("user {} logged in from {}", userId, ip) is compiled as if we had written log.debug("user {} logged in from {}", new Object[] {userId, ip}). That array is created by the caller, before the call instruction runs.
4 messages in order. Play them, or step through them one at a time.
The allocation happens before the logger can decide anything.
Notice that the early return inside debug() cannot help, because by the time it runs, the array is already on the heap. Primitive arguments make it worse, since each one is boxed into an Integer or Long object to fit into Object[] (small integers come from a cache, larger ones are new objects). The JIT can sometimes remove the allocation if it inlines debug() into the caller and sees that the array never escapes, but that depends on inlining budgets, and the profile in the question shows that across the fleet it often does not happen.
2Adding Fixed-Arity Overloads
The fix used by SLF4J, and by List.of for collections, is to add overloads that take a fixed number of arguments. Most log statements have zero, one or two arguments, so overloads up to three cover nearly every call.
Now the level check runs before any array exists, and when debug is disabled the call costs a field read and a branch. Inside the enabled path, the formatting code may still build an array internally, but only when a message is really written, which is the case we are happy to pay for.
Boxing of primitive arguments still happens at the call site, because the parameters are Object. That is usually a much smaller share than the arrays, and the cases where it matters are handled by the guards in a later section.
3Why This Is Source and Binary Compatible
Two kinds of callers exist, and both keep working. Callers that are recompiled against the new version go through overload resolution again. The compiler tries methods without varargs first, so a call with two arguments now matches debug(String, Object, Object) and stops creating an array. The behaviour must be identical to the varargs version, which is easy because both delegate to the same formatting code.
Callers that are not recompiled, such as services built months ago or third-party jars, contain a reference to the exact descriptor debug(String, Object[]). We did not remove or change that method, so they link and run exactly as before. They simply keep allocating until they are rebuilt. This is why adding overloads is safe in a minor release, whereas replacing the varargs method would not be.
| Caller | Method it calls | Allocates an array? |
|---|---|---|
| Recompiled, 0 to 3 arguments | matching fixed-arity overload | No |
| Recompiled, 4 or more arguments | debug(String, Object...) | Yes, as before |
| Old binary, any count | debug(String, Object[]), unchanged | Yes, as before |
4Keeping Every Call Shape Identical
Before release, we check that each overload behaves exactly like the varargs method did for the same arguments, because recompiled callers will silently switch to them. The trickiest case is a trailing exception. Many logging APIs treat a Throwable passed as the last argument as the exception to print with its stack trace, not as a value for a placeholder. So log.error("order {} failed", orderId, ex), which now calls the two-argument overload, must still recognise ex as the exception. If the new overload simply formatted both values, every recompiled service would lose its stack traces.
A caller that passes an explicit Object[] is safe: the compiler sees that both debug(String, Object) and debug(String, Object...) apply, picks the varargs one as more specific because Object[] is a subtype of Object, and passes the array as the argument list exactly as before. We still add a test for each shape, zero to four arguments, an explicit array and a trailing exception, run against the old and the new version, and compare the output line by line.
5Guards and Suppliers for Expensive Arguments
Overloads remove the array, but they cannot stop the caller from computing the arguments. A call like log.debug("state {}", order.toJson()) builds the JSON string every time, enabled or not. For those calls we have two tools.
The guard is explicit and costs nothing when disabled. The Supplier version reads better, but a lambda that captures a variable is itself an object, so on a disabled call it may still allocate a small object unless the JIT removes it. That is why the Supplier is for expensive arguments, not a replacement for the overloads. SLF4J 2 offers a fluent API, and Log4j 2 offers Supplier overloads, for the same purpose. Note that a Supplier overload next to an Object overload can make lambdas ambiguous, so it is often given its own method name.
6Measuring Before and After
We prove the change with allocation data rather than intuition. Java Flight Recorder, built into the JDK, samples allocations with their stack traces at low overhead, so we can record a few minutes on a busy instance, for example with jcmd <pid> JFR.start duration=300s filename=before.jfr, and look at allocation by stack in JDK Mission Control. Before the change, Object[] allocated from call sites of debug() should show up near the top; after rolling out recompiled services, it should disappear from those stacks.
Fleet-level numbers then show the real benefit: allocation rate per instance, young GC frequency and CPU spent in GC, compared over similar traffic. A JMH benchmark of a disabled debug call, run with -prof gc to report bytes allocated per operation, gives a clear unit-level result, typically going from about 24 bytes per call to 0.
7Follow-up questions
Why not just remove the varargs method and keep only the overloads?
Because already-compiled callers refer to debug(String, Object[]) by its descriptor and would fail with NoSuchMethodError. We also still need it for calls with more arguments than our largest overload.
Does escape analysis not solve this already?
Sometimes. If the JIT inlines debug() into the caller and sees the array never escapes, it can remove the allocation. But inlining depends on method size and call depth, and logging calls are spread across thousands of call sites, many not hot enough to be compiled that way. The fleet profile is the evidence that it does not reliably happen.
How many fixed-arity overloads should we add?
Enough to cover the common cases, which a scan of call sites can tell us. If 95 percent of calls have two arguments or fewer, overloads up to two or three cover them. Each extra overload adds API surface, so we stop where the data says the benefit ends.
8Conclusion
In this answer, we saw that a varargs logging call allocates its array at the call site, before the method can check the log level. Adding fixed-arity overloads for zero to three arguments removes that allocation for recompiled callers, while the unchanged varargs method keeps old binaries linking, so the change is both source and binary compatible. We checked that every call shape, including a trailing exception, behaves the same, used level checks or Supplier arguments for expensive values, and planned to confirm the improvement with JFR allocation profiles and a JMH benchmark with the GC profiler.
Open with
The root cause is that varargs are an array the compiler builds at the call site, so log(format, a, b) creates new Object[] {a, b}, plus boxing for primitives, before log even runs.
Then, if they want more
The level check inside the method is too late. My fix would be to add fixed-arity overloads, the way SLF4J and List.of do: log(String), log(String, Object), log(String, Object, Object), maybe three arguments, each checking the level first and only then formatting.
That is source compatible, because when services recompile, overload resolution prefers a fixed-arity method over varargs, so most calls move to an overload and stop allocating. It is binary compatible because I keep the varargs method unchanged, and old compiled callers link to that exact descriptor, so they keep working and just keep allocating until they rebuild.
One thing to test carefully is a trailing exception argument, which must still be treated as the exception after calls move to the new overloads. For expensive arguments like toJson(), overloads don't help, so I'd recommend an isDebugEnabled guard or a Supplier-based method.
Finally, I'd measure with JFR allocation profiling before and after, plus a JMH benchmark with the GC profiler, and watch young GC rates across the fleet.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A widely used internal logging API has a method log(String format, Object... args)....": https://scrivio-interview-library.netlify.app/java/arrays/8a14a8e153/