skip to content

On an inventory service's hot path, what does a disabled SLF4J `log.debug` call with four arguments still cost, and how would you measure that cost?

level: seniorimportance: should knowfreq 44%

answer

  1. call-site work happens first
  2. argument expressions run anyway
  3. boxing outside the small-integer cache
  4. no four-argument overload exists
  5. JMH with the GC profiler

basics

~20 s

The call still evaluates every argument expression, boxes primitive arguments and, with three or more arguments, allocates the varargs Object[] before the level check runs. Measure it with a JMH benchmark using the GC profiler, and JFR allocation sampling in production.

solid answer

~50 s

Placeholders only defer the formatting; everything at the call site still runs. For `log.debug("Reserved {} of {} for {} at {}", qty, sku, order.id(), warehouse.code())` Java evaluates `order.id()` and `warehouse.code()`, boxes `int qty` into an `Integer` (values outside the cached range, -128 to 127 by default, allocate), and, because `Logger` has no four-argument overload, builds an `Object[4]` for `debug(String, Object...)`. SLF4J's own `Logger` javadoc says the one- and two-argument overloads exist solely to avoid that hidden array. Only then does the provider check the level and return. To measure, write a JMH benchmark with DEBUG disabled, run it with `-prof gc` and read allocated bytes per operation; in production, JFR allocation sampling shows whether that call site really allocates. The JIT can sometimes remove the array and the box by escape analysis once the call inlines, which is why you measure instead of guessing.

code

java · 20 lines
java
@State(Scope.Benchmark)
public class DisabledDebugBenchmark {
    // provider configured so DEBUG is off for this logger
    static final Logger log = LoggerFactory.getLogger(DisabledDebugBenchmark.class);
    int qty = 1_000;
    String sku = "SKU-7";
    Order order = new Order("O-42");
    Warehouse warehouse = new Warehouse("W-3");

    @Benchmark
    public void fourArgs() {
        log.debug("Reserved {} of {} for {} at {}", qty, sku, order.id(), warehouse.code());
    }

    @Benchmark
    public void twoArgs() {
        log.debug("Reserved {} for {}", sku, order);
    }
}
// run with: java -jar benchmarks.jar DisabledDebugBenchmark -prof gc

go deeper

for a junior

Know that a disabled call still evaluates its arguments, so a method call inside a log statement runs even when nothing is printed.

for a middle

Explain the mechanics: boxing outside the small-integer cache, the Object[] built for three or more arguments, and why only one- and two-argument overloads exist.

for a senior

Show the judgement: prove the cost with JMH and -prof gc, confirm with JFR in production, account for escape analysis, and rewrite only the hot lines that matter.

for a principal

Weigh whether hot-path logging rules belong in a team standard or in targeted reviews, since blanket rules add noise to code where the cost is negligible.

## What disabled means at the call site A **disabled** log call is one whose level is below the logger's threshold, such as `debug(...)` when the logger is set to `INFO`. In SLF4J's classic API the level check happens **inside** the method: in the `AbstractLogger` base class that the providers in the SLF4J project extend, `debug(String, Object...)` begins with `if (isDebugEnabled())` and does nothing else when that is false. Message formatting is skipped, which is the whole point of `{}` placeholders. But Java evaluates a method's arguments **before** the method is entered, so everything needed to make the call still happens on every execution, enabled or not. ## The four costs of a disabled call | Cost | When it applies | Size | |---|---|---| | Argument expressions | any argument that is a method call, such as `order.id()` or `stock.summary()` | whatever that code costs, every time | | Boxing | a primitive argument such as `int qty` or `long nanos` | an `Integer`/`Long` allocation outside the box cache (-128 to 127 by default for `Integer`) | | The varargs array | three or more arguments, since only one- and two-argument overloads exist | one `Object[n]` per call | | The call and level check | always | an interface call plus the provider's enabled test | SLF4J's `Logger` javadoc for `debug(String, Object...)` describes the array as a hidden and relatively small cost that is paid even when the logger is disabled, and says the one- and two-argument variants exist solely to avoid it. On most code paths these costs are noise. On a hot path executed millions of times a second, such as a stock-reservation loop, they become allocation pressure and extra garbage-collection work. ## Measuring it Do not guess: the JIT compiler may remove some of this work, or may not, depending on inlining. 1. **Write a JMH benchmark** that calls the real logging line with the provider configured so DEBUG is off, and a baseline that does the same work without the log call. Return or consume results through a `Blackhole` so the compiler cannot discard the surrounding code. 2. **Run it with `-prof gc`** and read the normalised allocation rate (bytes per operation). A four-argument call with a boxed `int` typically shows the `Object[]` and the box; a two-argument version of the same line shows the difference the overloads make. 3. **Compare variants**: computed arguments against already-held references, four arguments against two. 4. **Confirm in production** with JFR's allocation sampling (`jdk.ObjectAllocationSample`), which attributes allocations to stack traces. If the logging call site does not show up, the benchmark's cost was absorbed or is irrelevant at real load. A zero-allocation benchmark result is not a proof: in a small benchmark the call may inline and **escape analysis** may scalar-replace the array and the box, while the real call site, deep in a large method or reached through a megamorphic interface call, may not inline at all. ## Reducing it without changing what is logged - **Pass references, not computed values.** `order` instead of `order.summary()` costs nothing when disabled; the object's `toString()` runs only if the line is actually formatted. This moves the cost, it does not hide it: an expensive `toString()` still costs when DEBUG is on. - **Stay within two arguments** on the hottest lines when one existing object already carries the fields, which avoids the varargs array. - **Avoid primitives that box** where an existing wrapper or object reference is available. - An enabled-check guard remains the bluntest tool, and the 2.0 fluent API's `Supplier` arguments are another option, covered with that API. ## A worked reading of the inventory hot path Take the reservation line `log.debug("Reserved {} of {} for {} at {}", qty, sku, order.id(), warehouse.code())` running inside a loop over order lines. Per execution with DEBUG off it performs two method calls, one `Integer` allocation whenever `qty` falls outside the cache, and one four-element array. Rewriting it as `log.debug("Reserved {} for {}", line, order)`, where `line` and `order` are objects the loop already holds and whose `toString()` prints the needed fields, removes the method calls, the box and the array from the disabled path while keeping the same information on the enabled one. ## The judgement Most services never need any of this; logging cost there is dominated by enabled lines and the backend's output path. The senior skill is knowing that a disabled call is **cheap, not free**, recognising the hot paths where cheap is multiplied by millions, and proving the effect with an allocation profile before rewriting log lines.

  • Your JMH run shows 0 bytes allocated per disabled call. Does that prove the production call site is free?
    No. In a tiny benchmark the call usually inlines, and escape analysis can scalar-replace the `Object[]` and the box. In the service the same line may sit in a large method or behind a megamorphic interface call that does not inline, so the allocation survives. Check the real call site with JFR allocation sampling, and remember argument expressions still cost CPU.
  • How does passing `order` instead of `order.summary()` change the cost of a disabled call?
    Passing a reference costs nothing extra, while `order.summary()` runs on every execution whether or not DEBUG is on. With the reference, `toString()` runs only when the line is actually formatted. The cost moves to the enabled case, so an expensive `toString()` still matters when someone turns DEBUG on.

  • A disabled placeholder call allocates nothing because formatting is deferred.
  • SLF4J evaluates the argument expressions lazily, only when the level is enabled.
  • Boxing an int argument never allocates thanks to the Integer cache.
  • A four-argument call has its own overload, so no array is created.
  • A JMH result of zero allocation proves the production call site is free.